Mongodb Primary Key: Example to set _id field with ObjectId()

What is Primary Key in MongoDB?

In MongoDB, _id field as the primary key for the collection so that each document can be uniquely identified in the collection. The _id field contains a unique ObjectID value.

By default when inserting documents in the collection, if you don’t add a field name with the _id in the field name, then MongoDB will automatically add an Object id field as shown below

Primary Key in MongoDB

When you query the documents in a collection, you can see the ObjectId for each document in the collection.

If you want to ensure that MongoDB does not create the _id Field when the collection is created and if you want to specify your own id as the _id of the collection, then you need to explicitly define this while creating the collection.

When explicitly creating an id field, it needs to be created with _id in its name.

Let’s look at an example on how we can achieve this.

db.Employee.insert({_id:10, "EmployeeName" : "Smith"})

Code Explanation:

  1. We are assuming that we are creating the first document in the collection and hence in the above statement while creating the collection, we explicitly define the field _id and define a value for it.

If the command is executed successfully and now use the find command to display the documents in the collection, the following Output will be shown

Output:

Primary Key in MongoDB

The output clearly shows that the _id field we defined while creating the collection is now used as the primary key for the collection.