MongoDB: How to get the last updated timestamp of the last updated document in a collection

34.5k views Asked by At

Is there a simple OR elegant method (or query that I can write) to retrieve the last updated timestamp (of the last updated document) in a collection. I can write a query like this to find the last inserted document

db.collection.find().limit(1).sort({$natural:-1})

but I need information about the last updated document (it could be an insert or an update).

I know that one way is to query the oplog collection for the last record from a collection. But it seems like an expensive operation given the fact that oplog could be of very large size (also not trustworthy as it is a capped collection). Is there a better way to do this?

Thanks!

3

There are 3 answers

2
Anirudh Bagri On

You could get the last insert time same way you mentioned in the question:

db.collection.find().sort({'_id': -1}).limit(1) 

But, There isn't any good way to see the last update/delete time. But, If you are using replica sets you could get that from the oplog.

Or, you could add new field in document as 'lastModified'. You can also checkout collection-hooks. I hope this will help

7
Damini Suthar On

You can try with ,

db.collection.findOne().sort({$natural:-1}).limit(1);
0
Balocodes On
  1. One way to go about it is to have a field that holds the time of last update. You can name it updatedAt. Every time you make an update to the document, you'll just update the value to the current time. If you use the ISO format to store the time, you'll be able to sort without issues (that's what I use).

  2. The other way is the _id field.

Method 1 db.collection.find().limit(1).sort({updatedAt: -1})

Method 2 db.collection.find().limit(1).sort({_id: -1})