WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

MongoDB - ObjectId


MongoDB - ObjectId

MongoDB - ObjectId In this chapter, we will learn the structure of ObjectId.

An ObjectId is a 12-byte BSON type having the following structure
  • The first 4 bytes representing the seconds since the unix epoch
  • The next 3 bytes are the machine identifier
  • The next 2 bytes consists of process id
  • The last 3 bytes are a random counter value
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document.

Creating New ObjectId

To generate a new ObjectId use the following code
>newObjectId = ObjectId()
when the above statement returned the following uniquely generated id

ObjectId(1024a02sd14ervc143")

Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id
>myObjectId = ObjectId("1024a02sd14ervc144")


Creating Timestamp of a Document

_id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document.
>myObjectId = ObjectId("1024a02sd14ervc144").getTimestamp()

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

ISODate("2018-10-12T21:49:17Z")

Converting ObjectId to String

you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code
>newObjectId.str

The above code will return the string format of the Guid −
1024a02sd14ervc144




Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.