MongoDb 时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12830161/
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:53:23  来源:igfitidea点击:

MongoDb timestamp

mongodbdatecollectionstimestampunix-timestamp

提问by Simba

i have created and want to now import a dummy collection. one of the fields in each item are "created" and "updated" fields. what can i put in the source/json file so that MongoDb will use the current date and time as the value on import?

我已经创建并希望现在导入一个虚拟集合。每个项目中的一个字段是“创建”和“更新”字段。我可以在源/json 文件中放入什么,以便 MongoDb 使用当前日期和时间作为导入值?

this wont work

这行不通

"created" : Date()

回答by Stennie

mongoimportis intended for importing data existingdata in CSV, TSV, or JSON format. If you want to insert new fields (such as a createdtimestamp) you will have to set a value for them.

mongoimport用于以CSV、TSV 或 JSON 格式导入数据现有数据。如果要插入新字段(例如created时间戳),则必须为它们设置一个值。

For example, if you want to set the createdtimestamp to the current time, you could get a unix timestamp from the command line (which will be seconds since the epoch):

例如,如果要将created时间戳设置为当前时间,则可以从命令行获取 unix 时间戳(这将是自纪元以来的秒数):

$ date +%s
1349960286

The JSON <date>representationthat mongoimportexpects is a 64-bit signed integer representing milliseconds since the epoch. You'll need to multiply the unixtime seconds value by 1000 and include in your JSON file:

JSON<date>表示mongoimport预计是整数,表示从epoch毫秒签订了64位。您需要将 unixtime 秒值乘以 1000 并包含在您的 JSON 文件中:

{ "created": Date(1349960286000) }

An alternative approach would be to add the created timestamps to documents after they have been inserted.

另一种方法是在插入文档后将创建的时间戳添加到文档中。

For example:

例如:

db.mycoll.update(
    {created: { $exists : false }},    // Query criteria
    { $set : { created: new Date() }}, // Add 'created' timestamp
    false, // upsert
    true   // update all matching documents
)   

回答by Salvador Dali

As Stennie correctly pointed out, you can not do this with just mongoimportor mongorestore: they are just for restoring your previously dumped data. Correct way of doing this is to restore the data and then to make update on the restored data.

正如 Stennie 正确指出的那样,您不能仅使用mongoimportor来执行此操作mongorestore:它们仅用于恢复您之前转储的数据。正确的方法是恢复数据,然后对恢复的数据进行更新。

With a new mongo 2.6 you can do this easily using $currentDateoperation, which was created to update time to a current timestamp.

使用新的 mongo 2.6,您可以使用$currentDate操作轻松完成此操作,该操作旨在将时间更新为当前时间戳。

In your case you need something like

在您的情况下,您需要类似的东西

db.users.update( 
  {},
  {
     $currentDate: {
      created: true,
      updated: true
     },
  }
)