Table of Contents
Objectid in Mongodb is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
You have seen the use of MongoDB ObjectId in previous chapters. In this chapter, we will understand the structure of ObjectId.
An ObjectId is a BSON type (12 bytes) with the following structure:
The first 4 bytes represent the number of seconds from UNIX Epoch.
The next 3 bytes is the machine id .
The next 2 bytes are the process id .
And the last 3 bytes are a random counting value .
MongoDB uses ObjectId as the default value of the _id field for each Document that is created while creating any Document. The complex combination of ObjectId makes all _id fields unique.
Create a new ObjectId in MongoDB
To create a new ObjectId, you use:
> newObjectId = ObjectId ()
The above command returns the following unique created id:
ObjectId ( "5349b4ddd2781d08c09890f3" )
In MongoDB, instead of creating ObjectId, you can also provide an ID of 12 bytes as follows:
> myObjectId = ObjectId ( "5349b4ddd2781d08c09890f4" )
Get the Timestamp of a Document
By default, _id ObjectId stores a Timestamp of 4 bytes in length, so in most cases, you do not need to store the creation time of any Document. You can get the creation time of a Document using the getTimestamp method:
> ObjectId ( "5349b4ddd2781d08c09890f4" ). getTimestamp ()
This command will return the creation time of this Document in ISO Date format:
ISODate ( "2014-04-12T21:49:17Z" )
Convert ObjectId into String in MongoDB
Next post: Map Reduce in MongoDB
FAQ
What should you know about get the Timestamp of a Document?
By default, _id ObjectId stores a Timestamp of 4 bytes in length, so in most cases, you do not need to store the creation time of any Document. You can get the creation time of a Document using the getTimestamp method:
What is Objectid in Mongodb?
You have seen the use of MongoDB ObjectId in previous chapters.
Why is Objectid in Mongodb important?
A clear understanding of Objectid in Mongodb helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.
Reader Comments 0
Sign in with email or Google to join the discussion.