MongoDb timestamp MongoDb timestamp mongodb mongodb

MongoDb timestamp


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 +%s1349960286

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)   


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