• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • AI
  • Blog

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.

Why do we need the ObjectId field? Well, MongoDB uses this as the primary key for the collection so that each document can be uniquely identified in the collection.

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


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.

Performing Queries

The method of fetching or getting data from a MongoDB database is carried out by using queries. While performing a query operation, one can also use criteria’s or conditions which can be used to retrieve specific data from the database.

MongoDB provides a function called db.collection.find () which is used for retrieval of documents from a MongoDB database.

During the course of this tutorial, you will see how this function is used in various ways to achieve the purpose of document retrieval.