
- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
Convert string to objectid in MongoDB?
To convert string to objectid in MongoDB, use $toObjectId. Let us create a collection with documents −
> db.demo95.insertOne({"Id":"5ab9cbe531c2ab715d42129a"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2d5ef5b8903cdd865577ac") }
Display all documents from a collection with the help of find() method −
> db.demo95.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a" }
Following is the query to convert string to objectid in MongoDB −
> db.demo95.aggregate([ { "$addFields": { "d" : { "$toObjectId": "$Id" } }} ])
This will produce the following output −
{ "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a", "d" : ObjectId("5ab9cbe531c2ab715d42129a") }
- Related Articles
- How to convert ObjectId to string in MongoDB
- MongoDB query to convert from ObjectId to String
- Create ObjectId in MongoDB using a seed string?
- How to generate ObjectID in MongoDB?
- Cast to ObjectId failed for value in MongoDB?
- Convert NumberLong to String in MongoDB?
- Display MongoDB records by ObjectId?
- Find a document with ObjectID in MongoDB?
- MongoDB query to update a MongoDB row with only the objectid
- MongoDB query to convert string to int?
- How to convert string to numerical values in MongoDB?
- How to return documents of a collection without objectId in MongoDB?
- Use ObjectId under findOne() to fetch a specific record in MongoDB?
- MongoDB query to convert numeric string to number
- How to convert value to string using $toString in MongoDB?

Advertisements