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

后端 未结 4 825
后悔当初
后悔当初 2021-02-12 12:18

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

4条回答
  •  星月不相逢
    2021-02-12 12:49

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

提交回复
热议问题