In MongoDB you must have ID for each collection you create and the data type that you can store in the ID field is limited only to arrays in other word you can use all kinds of data type including timestamp, integer, string and etc. But you cannot use array as your document id as this has to be one data but in array you can store multiple integer and string which mongo prevent you from adding array as your Document ID, as this is unique for each record you insert in MongoDB and it will use this for indexing your Document.

switched to db test
>{_id: 1})
>{_id: 3.45})
>{_id: "Niah"})
>{_id: ISODate()})

> db.omer.find()
{ "_id" : 1 }
{ "_id" : 3.45 }
{ "_id" : "Niah" }
{ "_id" : ISODate("2013-12-23T13:47:22.220Z") }

As you can see above code we have created all kinds of document ID and it works fine with MongoDB where as if we try to create a document ID as array you will see bellow screen as mongo preventing us from doing this.

>{_id : [1,4,5]})
_id cannot be an array

What is Object ID?

Let’s try another way to insert a Document without specifying its document ID:

Inserting record without ID Inserting record without ID and ID is assigned by ObjectID

As you can see we are able to do this and when you execute command to check the Document we just created you will see that ObjectID automatically assigned and created a ID for our Document what ObjectID does in MongoDB is it creates a dynamic ID for your collection which you don’t have to worry about uniqueness of your ID as every time you create a new document mongo automatically create that for you and this ID is used for indexing your collections for speed use.

Important: The relationship between the order of ObjectId values and generation time is not strict within a single second. If multiple systems, or multiple processes or threads on a single system generate values, within a single second; ObjectId values do not represent a strict insertion order. Clock skew between clients can also result in non-strict ordering even for values, because client drivers generate ObjectId values, not the mongod process.

ObjectID have many properties to use one of the most important property is timestamp of an object ID which is created automatically in collection:


You can also return the String value of an ObjectID by issuing the following command.


We can also return value of an object as hexadecimal by