【问题标题】:MongoDB: automagically capture created/updated time in the database (not the application)MongoDB:自动捕获数据库(不是应用程序)中的创建/更新时间
【发布时间】:2017-07-25 22:19:25
【问题描述】:

我想捕获插入到 MongoDB 数据库中的文档的插入和更新。对于插入,可以这样做,因为文档创建时间编码在 ObjectID 中。

例如,我可以插入一个文档:

> db.test.insertOne(
...    { docnum: 1}
... )
{
    "acknowledged" : true,
    "insertedId" : ObjectId("58bcee87fcf4a79f8157dfad")
}

...然后检索该文档的时间戳:

> ObjectId("58bcee87fcf4a79f8157dfad").getTimestamp()
ISODate("2017-03-06T05:07:19Z")

如果我随后更新该文档:

> db.test.updateOne(
...    { docnum: 1 },
...    {
...      $set: { "text": "Some text." }
...    }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

...文档时间戳不会改变,因为时间戳是创建时间戳,而不是最后更新的时间戳:

> db.test.find()
{ "_id" : ObjectId("58bcee87fcf4a79f8157dfad"), "docnum" : 1, "text" : "Some text." }

> ObjectId("58bcee87fcf4a79f8157dfad").getTimestamp()
ISODate("2017-03-06T05:07:19Z")

一个明显的解决方案是更改应用程序以包含更新的时间戳。在这种情况下,我不控制应用程序,只控制 MongoDB。

如果这是 MySQL,可以添加更新/创建的时间戳:

CREATE TABLE my_table (
  ...,
  updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  created TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

有与此等效的 MongoDB 吗?我读到 MongoDB 不支持触​​发器或存储过程,但我很想知道是否有常用的解决方法/hack 来做到这一点。

【问题讨论】:

标签: mongodb


【解决方案1】:

MongoDB 本身不保存任何时间戳。如果您使用的是 Mongoose,那么您可以指定在创建/更新时存储时间戳

var thingSchema = new Schema({..}, { timestamps: true });

http://mongoosejs.com/docs/guide.html#timestamps

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-08
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多