tarun nt
tarun nt

Reputation: 33

getting updated records from last 2 hours

I have a large amount of data in my MongoDB and I want to query those records which were updated in the last 2 hours. can someone help

Upvotes: 0

Views: 847

Answers (1)

Nicholas
Nicholas

Reputation: 2863

Pretty simple actually. First, add an updatedAt attribute at your collection. But I assume that you already have this.

So, in short:

db.collection.find({ "updatedAt" : { $lt: new Date(Date.now() - 2 * 60 * 60 * 1000) } })

If you did not have an updatedAt attribute, then this one is also possible.

db.collection.find({ $where: function () { 
  return Date.now() - this._id.getTimestamp() < (2 * 60 * 60 * 1000)  
} })

Explanation:

  1. You will find all documents whose updatedAt attribute is less than 7200 seconds.
  2. You will find all documents whose ObjectID is less than 7200 seconds.

Remember that ObjectID's timestamp can be retrieved.

Upvotes: 2

Related Questions