- MongoDB - PHP
- MongoDB - Java
- MongoDB - Deployment
- MongoDB - Create Backup
- MongoDB - Sharding
- MongoDB - Replication
- MongoDB - Aggregation
- MongoDB - Indexing
- MongoDB - Sorting Records
- MongoDB - Limiting Records
- MongoDB - Projection
- MongoDB - Delete Document
- MongoDB - Update Document
- MongoDB - Query Document
- MongoDB - Insert Document
- MongoDB - Data Types
- MongoDB - Drop Collection
- MongoDB - Create Collection
- MongoDB - Drop Database
- MongoDB - Create Database
- MongoDB - Data Modeling
- MongoDB - Environment
- MongoDB - Advantages
- MongoDB - Overview
- MongoDB - Home
Advanced MongoDB
- Auto-Increment Sequence
- MongoDB - Capped Collections
- MongoDB - GridFS
- Working with Rockmongo
- MongoDB - Regular Expression
- MongoDB - Text Search
- MongoDB - Map Reduce
- MongoDB - ObjectId
- MongoDB - Indexing Limitations
- MongoDB - Advanced Indexing
- MongoDB - Atomic Operations
- MongoDB - Analyzing Queries
- MongoDB - Covered Queries
- MongoDB - Database References
- MongoDB - Relationships
MongoDB Useful Resources
- MongoDB - Discussion
- MongoDB - Useful Resources
- MongoDB - Quick Guide
- MongoDB - Questions and Answers
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
MongoDB - ObjectId
We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand 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. The complex combination of ObjectId makes all the _id fields unique.
Creating New ObjectId
To generate a new ObjectId use the following code −
>newObjectId = ObjectId()
The above statement returned the following uniquely generated id −
ObjectId("5349b4ddd2781d08c09890f3")
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Creating Timestamp of a Document
Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
This will return the creation time of this document in ISO date format −
ISODate("2014-04-12T21:49:17Z")
Converting ObjectId to String
In some cases, 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 −
5349b4ddd2781d08c09890f3Advertisements