Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve last update time of each document in MongoDB?

Tags:

I would like to know if there is a way to get the last update/modify time of data (i.e documents) in a collection in MongoDB. More clearly, I want to make a query to retrieve all documents updated after a particular time.

Is there any possible ways to retrieve this last modified timestamp in MongoDB?

Note: For newly created documents, I know that we can retrieve the timestamp from the objectId, but for an update, the id is going to be same. Does MongoDB store the last update time for each document anywhere?

I am using morphia as the java driver, so if there is any possible way from morphia, please let me know.

like image 907
Sadish Kumar Avatar asked Dec 20 '12 09:12

Sadish Kumar


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?

Working of the timestamp in mongodb is simple, where when executed, the timestamp method will call the currentDate(), which will pick the current date and time of the system. This picked date and time will be stored in the collection, along with the other data values.

Does MongoDB add a timestamp?

Making sure that all your applications create and update MongoDB timestamps is going to be the hardest part of this process; MongoDB has no automatic timestamp support, so every one of your applications is going to have to make sure they do one of two things when working with the database: write a createdAt field, or ...

How do I find recent entries in MongoDB?

find(). sort({x:1}); The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.) If you use the auto created _id field it has a date embedded in it ... so you can use that to order by ...


1 Answers

You need to capture last update time yourself.

For my application, I keep an AuditTrail object, which captures AuditEvents. These events occur on any insert, update, or delete of an object (delete is virtual in my system, just setting a flag).

For each AuditEvent, I keep track of the date, authenticated user, db action, and a description filled in by the application. This is implemented in PersistentObject, so it is automatically called for any database action of any object saved in Mongo.

This actual took very little time to implement, but provides both the ability to get the last update time, and also any other information that you may need for security and customer support for everything in Mongo.

like image 74
Ramesh Avatar answered Sep 21 '22 17:09

Ramesh