I am porting over a table of articles from MySQL to Mongo DB. I understand that the _id field generated by Mongo has the time of creation somehow in there and can be extracted or you can query against it. Because of this, I want to use it to have my created_time INT timestamp from MySQL. Is there a way when moving my data to generate an _id for Mongo that will have the time stamp that I currently have for my records in a separate field?
Asked
Active
Viewed 2,242 times
1 Answers
3
Yes, that's possible. In the C# driver for instance, there's a constructor for ObjectId
where you can pass in a timestamp, see this source file. It's easiest to use the helper method GenerateNewId
:
var id = ObjectId.GenerateNewId(new DateTime(2012, 01, 01));
I don't know which programming language you're using and whether the driver in that language supports this feature, but I guess this is widely available.
EDIT: This question contains the code for Java, mongoose and python, and the answer contains code for PHP. "Widely available" seems to be a wrong assumption, it's not yet implemented in the PHP driver, for instance.
-
Hah, I'm actually using PHP. Not surprised of it's limits but I didn't think that would matter. Is there a way to generate the MongoId using the new DateTime() object by sending a raw query to Mongo instead of using the driver to do it or an alternative approach for PHP users? – Glitches Mar 18 '13 at 18:18
-
The referenced source file has moved. As of today it is at: https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Bson/ObjectModel/ObjectId.cs – GaTechThomas Aug 24 '15 at 18:55