Loading

Mongo DB

What is Primary Key in MongoDB?. The Complete Mongo DB Developer Course 2023 [Videos].

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

Mongodb ObjectId()

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:

Mongodb ObjectId()

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

See All

Comments (194 Comments)

Submit Your Comment

See All Posts

Related Posts

Mongo DB / Youtube

What is MongoDB and why use it?

MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.
27-dec-2020 /4 /194

Mongo DB / Youtube

What is the difference between a document and a collection in MongoDB?

Databases, collections, documents are important parts of MongoDB without them you are not able to store data on the MongoDB server. A Database contains a collection, and a collection contains documents and the documents contain data, they are related to each other.
27-jan-2021 /4 /194

Mongo DB / Youtube

What is MongoDB and why use it?

MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.
24-May-2021 /4 /194