1

i've to run a query like this (sql) in MongoDb 4:

SELECT * FROM log WHERE DATE_ADD(created_at, INTERVAL 2 HOUR) < NOW()

Basically, I want to find all the documents, in the PENDING state, whose creation date PLUS TWO HOURS is less than now .. Let me explain: I want to find all the documents in the PENDING state that have been in PENDING for more than two hours. I feel stupid, but I am failing to do this with MongoDb. I also created a playground:

https://mongoplayground.net/p/4bifqiX2KMJ

Can you help me?

1 Answer 1

1

You can add hours in ISO date using $add, convert string date to ISO date using dateFromString,

let date = new Date();

db.collection.find({
  status: "pending",
  $expr: {
    $lt: [
      {
        $add: [
          // convert string date to ISOdate, if its already then use only "$inserted_at"
          { $dateFromString: { dateString: "$inserted_at" } },
          // add milliseconds
          7200000 // (60*60*2000)
        ]
      },
      date
    ]
  }
})

Playground


Or subtract from current date and then compare the condition,

let date = new Date();
date = new Date(date.getHours()-2); //subtract 2 hours

db.collection.find({
  status: "pending",
  $expr: {
    $lt: [
      { $dateFromString: { dateString: "$inserted_at" } },
      date
    ]
  }
})

Playground

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your reply, but I am not understanding: the two hours must be added to the date of the document itself, not to the current date or to a preset date. I have to find, as written, all the documents in "Pending" status where the insert_at plus two hours is in the past ..
Have you check and experiment with first example? that is similar to your select query. I have to find, as written but your mysql select query will find written?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.