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 al
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.
No, MongoDB by itself does not store either creation or update timestamps. You have to do that yourself (and as you have found out, if you use an ObjectID _id then you get the creation date already).
You can do the following. With MongoDB version 4.2+, you can now perform aggregation operators like $toDate
to extract the timestamp from ObjectId "_id" and update
at the same time.
Here we use the aggregate query $toDate
to extract the timestamp from MongoDB's ObjectId "_id" field and update the documents using {$replaceRoot: {newRoot: "$$ROOT"}}
instead of explicitly stating $set
var collection = "person"
agg_query = [
{
"$addFields" : {
"_last_updated" : {
"$toDate" : "$_id"
}
}
},
{
$replaceRoot: {
newRoot: "$$ROOT"
}
}
]
db.getCollection(collection).updateMany({}, agg_query, {upsert: true})
You can either use an audit trail entity as @user1530669 mentioned (I'm calling mine delta - the code is already available somewhere on StackOverflow).
Or you can simply save the last change time. I'm generally using a base entity to set that up and all other entities extend it (for your specific requirement you can probably remove the creationDate
as the lastChange
is enough for you):
protected Date creationDate;
protected Date lastChange;
// Getters and setters or final setters which don't do anything,
// if you only want to allow the entity to update the values
@PrePersist
public void prePersist() {
creationDate = (creationDate == null) ? new Date() : creationDate;
lastChange = (lastChange == null) ? creationDate : new Date();
}
And in your queries you can then add a filter so that the lastChange
attribute is more recent than your retrieval limit.