

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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?
- Display MongoDB records by ObjectId?
- Cast to ObjectId failed for value in MongoDB?
- Convert NumberLong to String in MongoDB?
- 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?
- MongoDB query to convert numeric string to number
- How to convert string to numerical values in MongoDB?
- Use ObjectId under findOne() to fetch a specific record in MongoDB?
- How to return documents of a collection without objectId in MongoDB?
- How we can perform sort on ObjectId column in MongoDB?
Advertisements