mongodb 如何检索MongoDB中每个文档的最后更新时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13968700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:58:47  来源:igfitidea点击:

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

mongodbmorphia

提问by Sadish Kumar

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.

我想知道是否有办法获取 MongoDB 集合中数据(即文档)的最后更新/修改时间。更清楚的是,我想进行查询以检索特定时间后更新的所有文档。

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

有没有可能的方法来检索 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?

注意:对于新创建的文档,我知道我们可以从 objectId 中检索时间戳,但是对于更新,id 将是相同的。MongoDB 是否将每个文档的最后更新时间存储在任何地方?

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

我使用 morphia 作为 java 驱动程序,所以如果有任何可能的方法来自 morphia,请告诉我。

回答by Ramesh

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

对于我的应用程序,我保留了一个 AuditTrail 对象,用于捕获 AuditEvents。这些事件发生在对象的任何插入、更新或删除(删除在我的系统中是虚拟的,只是设置一个标志)。

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.

对于每个 AuditEvent,我会跟踪日期、经过身份验证的用户、数据库操作和应用程序填写的描述。这是在 PersistentObject 中实现的,因此它会自动调用保存在 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.

这实际上花费了很少的时间来实现,但提供了获取上次更新时间的能力,以及您可能需要的任何其他信息,用于对 Mongo 中的所有内容进行安全和客户支持。

回答by Thilo

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

不,MongoDB 本身不存储创建或更新时间戳。您必须自己执行此操作(正如您所发现的,如果您使用 ObjectID _id,那么您已经获得了创建日期)。

回答by xeraa

You can either use an audit trail entity as @user1530669 mentioned (I'm calling mine delta - the code is already available somewhere on StackOverflow).

您可以使用@user1530669 提到的审计跟踪实体(我正在调用我的 delta - 代码已经在 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 creationDateas the lastChangeis enough for you):

或者您可以简单地保存上次更改时间。我通常使用一个基本实体来设置它,所有其他实体对其进行扩展(对于您的特定要求,您可以删除它,creationDate因为它对您lastChange来说已经足够了):

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 lastChangeattribute is more recent than your retrieval limit.

然后在您的查询中,您可以添加一个过滤器,以便该lastChange属性比您的检索限制更新。

回答by Yi Xiang Chong

You can do the following. With MongoDB version 4.2+, you can now perform aggregation operators like $toDateto extract the timestamp from ObjectId "_id" andupdateat the same time.

您可以执行以下操作。随着MongoDB的4.2以上版本,您现在可以进行聚合运营商想$toDate从中提取的ObjectId时间戳“_id” ,并update在同一时间。

Here we use the aggregate query $toDateto extract the timestamp from MongoDB's ObjectId "_id" field and update the documents using {$replaceRoot: {newRoot: "$$ROOT"}}instead of explicitly stating $set

这里我们使用聚合查询$toDate从 MongoDB 的 ObjectId "_id" 字段中提取时间戳,并使用{$replaceRoot: {newRoot: "$$ROOT"}}而不是显式声明更新文档$set

var collection = "person"

agg_query = [
    {
        "$addFields" : {
            "_last_updated" : {
                "$toDate" : "$_id"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: "$$ROOT"
        } 
    }
]

db.getCollection(collection).updateMany({}, agg_query, {upsert: true})