How explicitly give the object id in mongoDB?

47 views
Skip to first unread message

yrsna....@gmail.com

unread,
Jun 21, 2015, 2:44:15 AM6/21/15
to mongod...@googlegroups.com

Hi, 


objectId in mongoDB is of total 12 bytes hexadecimal number is unique for every document in a collection. which is a combination of 4 bytes timestamp, 3 bytes of machine id, 2 bytes of process id and 3 bytes of incrementer or random counter.

if we do not mention the _id field explicitly it is inserted by the sever itself.

if one wants to insert the _id field, how it should be constructed explicitly??

ex:

db.mycol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'example',
   url: 'http://example.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})


In the above example _id: ObjectId(7df78ad8902c) this bold part. how this 12 bytes id is constructed manually?


Thanks

Bernie Hackett

unread,
Jun 21, 2015, 1:29:33 PM6/21/15
to mongod...@googlegroups.com, yrsna....@gmail.com
Most language drivers will add the _id field on insert if the document to insert does not already include it. If a driver doesn't do this the server will add _id to the inserted document. All official MongoDB drivers have an ObjectId implementation you can use to generate _id values, but note that _id does not have to be and instance of ObjectId. It just has to be a unique value:

Reply all
Reply to author
Forward
0 new messages