Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 220
void Avatar asked Dec 06 '17 08:12

void


People also ask

How can I see when a document was last updated in MongoDB?

To get last inserted document, use sort() along with limit(1).

How is Timestamp stored in MongoDB?

MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.

Does MongoDB have Timestamp?

The MongoDB timestamp looks similar to Date data type, where it has the same 64-bit value. But it also has a few aspects where it differs from the Date. The MongoDB Timestamp is quite used for the internal purpose, and with every single instance of mongodb, the values generated for timestamp are unique.


2 Answers

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

like image 74
Anirudh Bagri Avatar answered Oct 20 '22 23:10

Anirudh Bagri


  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})

like image 27
Balocodes Avatar answered Oct 21 '22 00:10

Balocodes