Aluthren
Aluthren

Reputation: 452

Filter mongo documents by calculated date

I'm trying to filter a read query by a calculated date. Specifically, I want to get all documents whose creationDate field value is older than 24 hours from the current date. The following is what I've got, but it returns nothing:

db.user.find({creationDate: {$lt: {$subtract: [new Date(), 24 * 3600 * 1000]} }})

At first I thought it might be a data type issue, but the following query returns the expected documents:

db.user.find({creationDate: {$lt: new Date()}})

and the following, contrived, query confirms that the $subtract command returns a date:

> db.user.aggregate([{$project: {dateDifference: {$subtract: [new Date(), 24 * 3600 * 1000]}}}, {$limit: 1}])
[
  {
    _id: ObjectId("6057bce0ab02f3489f1d22c1"),
    dateDifference: 2021-05-17T01:23:15.260Z
  }
]

Not sure what I'm doing wrong in the first query.

Upvotes: 1

Views: 58

Answers (1)

zx01
zx01

Reputation: 571

You can get the desired result without making use of $subtract aggregation.

db.user.find({
  creationDate: {
    $lt: new Date(Date.now() - 24 * 3600 * 1000)
  }
})

Upvotes: 4

Related Questions