For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentWhat Is Objectid in Mongodb and How to Generate It Manually

What Is Objectid in Mongodb and How to Generate It Manually

Published
05th Sep, 2023
Views
view count loader
Read it in
7 Mins
In this article
    What Is Objectid in Mongodb and How to Generate It Manually

    MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of using tables and rows as in the traditional relational databases, MongoDB makes use of collections and documents.

    You can read more about MongoDB here.

    What are documents and collections?

    • Collection: A collection is a group of MongoDB documents, and is similar to a table in a SQL(RDBMS) Database. A collection exists within a single database. Collections do not enforce a schema(structure). Documents within a collection can have different fields. Typically, all documents in a collection are of a similar or related purpose. 
    • Documents: A document is a set of key-value pairs. Documents have dynamic schema(structure). Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.

    To know more about web development, check out  what is Full Stack Development course.   

    An example of a MongoDB document is shown below:

    {
       _id: ObjectId(7df78ad8902ce46d)
       title: 'Awesome Post',   
       description: 'This is an awesome post',
       tags: ['tours', 'photography'],
       likes: 100,  
       comments: [
          {
             user:'user1',
             message: 'My first comment',
             dateCreated: new Date(2011,1,20,2,15),
             like: 0  
          },
          {
             user:'user2',
             message: 'My second comments',
             dateCreated: new Date(2011,1,25,7,45),
             like: 5
          }
       ]
    }

    _id is a 12 bytes hexadecimal number which assures the uniqueness of every document. It is called ObjectId.

    In this blog we are going to learn about MongoDB, ObjectId and how to generate it manually.

    Why use MongoDB?

    • It is document oriented: The document data model is a powerful way to store and retrieve data that allows developers to move fast.
    • High performance: MongoDB’s horizontal, scale-out architecture can support huge volumes of both data and traffic.

    Data Representation in JSON or BSON. An example of a JSON object is given below.

    {
      "name" :  "Carlos Smith",
      "title" : "Product Manager",
      "location" : "New York, NY",
      "twitter" : "@MongoDB",
      "facebook" : "@MongoDB"
    }

    You can read more about the use cases of MongoDB here.

    What is the difference between MySQL and MongoDB?

    The major and the key differences between MySQL and MongoDB are listed here:

    MongoDB is an open-source database developed by MongoDB, Inc. MongoDB stores data in JSON-like documents that can vary in structure. It is a popular NoSQL database.

    MySQL is a popular open-source relational database management system (RDBMS) that is developed, distributed and supported by Oracle Corporation. MySQL uses tables to store the data.You can read more about the differences here.

    How to install MongoDB locally?

    Let's go through the installation separately for Windows and Linux operating systems.

    • Windows: Navigate to the below mentioned link and click on the download button to download the zip file, as you can see in the image.

    Link to download MongoDB.

    What Is Objectid in Mongodb and How to Generate It Manually

    You can unzip and run the file to install MongoDB for Windows.

    • Linux: You can simply run the below command inside the terminal to install MongoDB.
    • Command: sudo apt-get install mongodb
      What Is Objectid in Mongodb and How to Generate It Manually

    Now, run the below command inside the command prompt, powershell or terminal to start MongoDB shell where we can create the Object IDs for this blog. 

    • Command: mongo

    What Is Objectid in Mongodb and How to Generate It Manually

    It's important to know that MongoDB uses BSON format to store data.

    Difference between JSON and BSON:

    As we have already seen how JSON looks, now let's take a look at BSON and understand the differences between JSON and BSON.

    BSON stands for binary JSON (a superset of JSON with some more data types, most importantly binary byte array).

    You can read more about the differences here.

    What is ObjectId in MongoDB?

    • As you see, in the example of a MongoDB document the _id field is called Object ID. MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document.
    • Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. 
    • Syntax: ObjectId(<hexadecimal>).
    • An ObjectId is a 12-byte BSON type hexadecimal string having the structure as shown in the example below.
      Example: ObjectId("6009c0eee65f6dce28fb3e50") 
    • The first 4 bytes are a timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch.
    • Next 5-bytes represent a  random value.

    Note: Object ID is a unique identifier for each record which is created by declaring ObjectId as a method, as you will now see. Do not get confused between Object ID and ObjectId.

    Creating a new ObjectId:

    To create a new Object ID manually within the MongoDB you can declare ObjectId as a method. In the below image you can observe that we are declaring a variable having ObjectId method as a value. It will return a unique hexadecimal which we can store in a variable named myObjectId.

    Not sure how to kick-start your career as a web designer? Enroll in Web Designing Certifications.   

    • Command: myObjectId = ObjectId()

    What Is Objectid in Mongodb and How to Generate It Manually

    In this example, the value of myObjectId would be: ObjectId("6009cb85e65f6dce28fb3e51").

    In the above image, you can observe that each time it is returning a unique hexadecimal value.

    Specify a Hexadecimal String:

    Sometimes you want to define your own unique hexadecimal value, and MongoDB allows you to perform this action. In the above example the hexadecimal value is generated.

    In this scenario, we will define an object ID with a hexadecimal value as a parameter of the ObjectId method.

    • Command: newObjectId = ObjectId("507f1f77bcf86cd799439011")

    What Is Objectid in Mongodb and How to Generate It Manually

    In this example, the value of newObjectId would be: ObjectId("507f1f77bcf86cd799439011").

    Access the Hexadecimal String:

    In the above examples we are unable to get the hexadecimal string, as it will return you the whole method having the unique hexadecimal value.

    To extract the unique hexadecimal as a string from the Object ID, we need to use ‘str’ attribute which is available in ObjectId method.

    • Command: ObjectId("507f191e810c19729de860ea").str

    What Is Objectid in Mongodb and How to Generate It Manually

    In this example, the value of the ObjectId("507f191e810c19729de860ea").str method returned the hexadecimal string which is inside ObjectId method.

    Methods available upon ObjectId:

    • Note: We already have newObjectId with us so we can test these methods using the same variable.
    • Method: ObjectId.getTimestamp().
    • Explanation: Returns the timestamp portion of the object as a Date.
    • Command: newObjectId.getTimestamp()

    What Is Objectid in Mongodb and How to Generate It Manually

    This will return the creation time of this document in ISO date format.

    • Method: ObjectId.toString()
    • Explanation: Returns the string representation of the ObjectId(). This string value has the format of ObjectId(<hexadecimal>).
    • Command: newObjectId.toString()

    What Is Objectid in Mongodb and How to Generate It Manually

    This will return the ObjectId(<hexadecimal>) of this document in string format.

    • Method: ObjectId.valueOf()
    • Explanation: Returns the value of the ObjectId() as a lowercase hexadecimal string. This value is the str attribute of the ObjectId() object.
    • Command: newObjectId.valueOf()

    What Is Objectid in Mongodb and How to Generate It Manually

    Note that the returned values of newObjectId.valueOf() and newObjectId.str are the same.

    Unleash your coding potential with our Python Beginner Course. Dive into the world of programming and discover the power of Python. Start your journey today!

    What you have learnt

    • What is MongoDB and why do we use it?
    • Differences between MySQL and MongoDB Databases
    • How to install mongodb locally in Windows and Linux Operating systems.
    • Differences between JSON and BSON documents
    • What is ObjectId and its importance 
    • Generating a new ObjectId manually 
    • Methods available over Object Id and how to use them.

    MongoDB is a NoSQL DB that is widely used in the industry, and also easy to learn. Good luck!

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon