9

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()
Alex Bitek
  • 6,529
  • 5
  • 47
  • 77
Simba
  • 522
  • 1
  • 5
  • 9

2 Answers2

14

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
)   
Stennie
  • 63,885
  • 14
  • 149
  • 175
  • What about if the field is an ISODate? I have noticed that the Date(timestamp) produces a string, and ISODate(sametimestamp) produces a completely different and unexpected date. How to convert from the string to the ISODate format ? – Ketema Dec 18 '12 at 23:22
  • 4
    The [`ISODate()` function](https://github.com/mongodb/mongo/blob/v2.2/src/mongo/shell/utils.js#L400) is a convenient helper to create `Date()` objects. The `ISODate()` constructor expects an ISO8601-style date/time string, while `Date()` expects a unixtime (seconds since the epoch). If you try `new Date()` and `new ISODate()` in the `mongo` shell you should see they both produce the same value (an `ISODate`). Both formats have the same [BSON representation](http://bsonspec.org/#/specification), which is a UTC datetime. – Stennie Dec 19 '12 at 20:20
3

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
     },
  }
) 
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753