Max Block
Max Block

Reputation: 1444

How to create a mongodb query using current time and another field from the documents?

There are some data in the collection:

db.test.insertMany([
    { name: "n1", interval: 10, checked_at: new ISODate("some datetime") },
    { name: "n2", interval: 20, checked_at: new ISODate("some datetime") },
    { name: "n3", interval: 30, checked_at: new ISODate("some datetime") }])

It's necesssary to find all documents where $checked_at are older than $interval seconds from the current moment.

Here is a pseudo code for this request:

db.test.find({"checked_at": {"$lt": "NOW()-$interval"}});

Upvotes: 0

Views: 19

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

I think you have to use an aggregation pipeline:

db.test.aggregate([
   {
      $match: {
         $expr: {
            $lt: ["$checked_at", { $subtract: ["$$NOW", { $multiply: ["$interval", 1000] }] }]
         }
      }
   }
])         

Upvotes: 1

Related Questions