jrdhawk
jrdhawk

Reputation: 11

MongoDB find all documents where field 1 is seven days or more after field 2

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.

Upvotes: 1

Views: 312

Answers (1)

YuTing
YuTing

Reputation: 6629

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

Upvotes: 1

Related Questions