1

I need to search through a large mongo collection and find all the documents where updatedAt is at least 7 days after createdAt.

My data looks basically like this:

"createdAt" : ISODate("2021-04-03T10:17:21.256Z"),
"updatedAt" : ISODate("2021-04-03T10:17:21.256Z")

I would appreciate any help.

YuTing
  • 6,555
  • 2
  • 6
  • 16
jrdhawk
  • 11
  • 2

1 Answers1

1

Use $expr in match. $dateAdd is only available in mongodb 5.0.

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $gt: [
          "$updatedAt",
          {
            $dateAdd: {
              startDate: "$createdAt",
              unit: "day",
              amount: 7
            }
          }
        ]
      }
    }
  }
])

mongoplayground


Use $expr in match. $add .

604800000 = 7 * 24 * 60 * 60 * 1000

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $gt: [
          "$updatedAt",
          {
            $add: [
              "$createdAt",
              604800000
            ]
          }
        ]
      }
    }
  }
])

mongoplayground


use $where

db.collection.find({
  "$where": "this.updatedAt > new Date(this.createdAt.getTime() + 604800000)"
})

mongoplayground

YuTing
  • 6,555
  • 2
  • 6
  • 16
  • Thank you very much for your answer. It looks like we use an older version of Mongo so I'll see what I can do based on your answer. I appreciate it. – jrdhawk Jan 28 '22 at 20:26
  • @jrdhawk I update my answer with `$add` – YuTing Jan 29 '22 at 02:29
  • Thank you so much for your help. I'm still having some trouble. It looks like we use Mongo 3.6.0. I keep getting: Failed to execute script. Error: Uncaught exception: Error: command failed: { "ok" : 0, "code" : 303, "errmsg" : "Feature not supported" } : aggregate failed : _getErrorWithCode@src/mongo/shell/utils.js:25:13 – jrdhawk Jan 31 '22 at 21:38
  • @jrdhawk I think [`$expr`](https://docs.mongodb.com/v4.2/reference/operator/query/expr/) and with `$gt` and `$add` are available in mongodb 3.6 – YuTing Feb 01 '22 at 03:21
  • @jrdhawk I update my answer with [`$where`](https://docs.mongodb.com/manual/reference/operator/query/where/) – YuTing Feb 01 '22 at 03:31
  • So I just found out all our databases are mongo except this one and it's DocumentDB. I'm sure all your answers would have worked had I been querying Mongo like I thought. Sorry for my mistake and thanks for taking the time. I will still use these with Mongo. – jrdhawk Feb 01 '22 at 18:01
  • @jrdhawk accept this answer since it really solve your original problem, – YuTing Feb 02 '22 at 02:07
  • Or even use `db.collection.find`. [mongoplayground.net](https://mongoplayground.net/p/HL7MopDuToI) – rickhg12hs Feb 02 '22 at 02:43
  • @YuTing Again thanks for your info. I think the main problem is DocumentDB isn't compatible with $expr or $where according to the docs https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html#mongo-apis-query – jrdhawk Feb 02 '22 at 18:24