Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb timestamp

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()
like image 624
Simba Avatar asked Oct 10 '12 23:10

Simba


1 Answers

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
)   
like image 180
Stennie Avatar answered Nov 08 '22 23:11

Stennie