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") }

Updated on: 30-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements