Nathan
Nathan

Reputation: 1

mongoimport include the time of import

I am currently using mongoimport like this to import many JSON files into my database.

mongoimport --host localhost --db test --collection <collectionName> --type json --file <filepath>

This works well, however, I want to add a field that records the timestamp of the time of import (I am using a cron job so this script runs at various times). How exactly can I do this?

Upvotes: 0

Views: 976

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

When the documents get created during import, you get a primary key that's created for you called '_id' which has an ObjectId type field.

As it turns out the first four bytes of the ObjectId are the timestamp of its creation. So you can sort by _id as a proxy for sort by insert time, in addition various MongoDB drivers provide methods to extract the timestamp from the ObjectId - for example in MongoDB shell:

> var o=new ObjectId()
> o
ObjectId("51ae926b77bf7c394dfe0cc8")
> o.getTimestamp()
ISODate("2013-06-05T01:20:43Z")

Upvotes: 1

Related Questions