- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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") }
Advertisements