The ObjectId of any document consists of a hexadecimal number and can be used to identify any document uniquely. It is observed that the system-defined ObjectIds are always unique. Similarly, users cannot assign a single id value to multiple documents.
This tutorial provides a brief guide to learn the possible ways of getting ObjectId after insert. Before getting a deep insight, let’s start this guide to understand the assignment of ObjectId in MongoDB.
What is the difference between system-defined and user-defined unique id’s
As discussed earlier, all the documents in MongoDB contain unique ids that are categorized into two broad categories. i.e., User Defined and System Defined. Here, we have prepared a section that explains both sections.
System Defined ids: If the user forgot to add an “_id” field during the insertion process, the system automatically assigns an ObjectId to that document. For instance, the command given below inserts two fields in the staff collection. It is to notice that we have not provided any unique id during insertion:
Let’s check the content inside staff collection by issuing the below-mentioned command:
It is observed from the output that the system has assigned an ObjectId, as we had not provided the id while inserting the document.
User-Defined ids: To better understand user-defined Ids, we have followed the below-mentioned command to insert a document in employees collection. It can be observed that the command contains an “Id” field.
Verify the insertion by issuing the following command:
And you will notice from the output that the “_id” field contains the same value as it was inserted in the command above.
How to get the ObjectId after insert
This section contains the best possible way to get the “ObjectId” after insertion in MongoDB. The collection name is “Authors” and will be used here to refer to the examples.
The common method to get the ObjectId of documents is by using the find method. The below-mentioned command will retrieve all the content from the “Authors” collection. It is observed that the first field of each document contains the Id of each document that uniquely identifies that document.
Conclusion
One of the primary properties of any Database Management System(DBMS) is to uniquely identify the stored data. Like other DBMSs, MongoDB also assigns a unique id to each document inside a collection. In this guide of the MongoDB series, you have learned the way to get the ObjectId after inserting it in MongoDB. To check the ObjectId in MongoDB, the find() method is frequently practiced. The ObjectId in MongoDB is assigned by the system and is long in length as well. Therefore, it is impossible to remember lengthy unique ids for hundreds of documents. By following this guide, you would be able to check for ObjectId of all documents and then you can access the documents by using their unique Id’s.