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