MongoDb timestamp

若如初见. 提交于 2019-12-10 03:05:28

问题


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?

this wont work

"created" : Date()

回答1:


mongoimport is intended for importing data existing data in CSV, TSV, or JSON format. If you want to insert new fields (such as a created timestamp) you will have to set a value for them.

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

$ date +%s
1349960286

The JSON <date> representation that mongoimport expects 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:

{ "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
)   



回答2:


As Stennie correctly pointed out, you can not do this with just mongoimport or 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.

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

In your case you need something like

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


来源:https://stackoverflow.com/questions/12830161/mongodb-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!