Its very complex combination of Objectids makes all the _id fields unique. We have option to into own value into _id field.
Object ID= [4 bytes seconds since epoch, 3 bytes machine hash, 2 bytes process ID, 3 bytes counter]
An ObjectId is a 12-byte BSON type having the following structure:
• The first 4 bytes representing the seconds since the unix epoch
• The next 3 bytes are the machine identifier
• The next 2 bytes consists of process id
• The last 3 bytes are a random counter value
Benefit of ObjectIDs
To generate a new ObjectId use the following code:
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id:
We can insert own unique value for _id.
db.foo.insert({_id: ‘abc’})
Objectid store 4 byte tmestamp. You can fetch the creation time of a document using getTimeStamp function :
when you will run command on console. This will return the creation time of this document in ISO Date format:
ISODate(“2015-05-27T09:00:17Z”)
In some cases you may need the value of ObjectId in string format. To convert the ObjectId in string use the following code:
x.str (x is object here)Or
ObjectId(“556587a1461650e970aec7a0”).str
this command will return the string format of object like this
556587a1461650e970aec7a0