Cast to ObjectId failed for value in MongoDB?


To cast to ObjectId correctly, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo460.insertOne({"_id":"5ab9cbfa31c2ab715d42129e"});
{ "acknowledged" : true, "insertedId" : "5ab9cbfa31c2ab715d42129e" }

Display all documents from a collection with the help of find() method −

> db.demo460.find();

This will produce the following output −

{ "_id" : "5ab9cbfa31c2ab715d42129e" }

Following is the query to cast to objectId −

> db.demo460.aggregate( [ idConvert ])

This will produce the following output −

{ "_id" : "5ab9cbfa31c2ab715d42129e", "value" : ObjectId("5ab9cbfa31c2ab715d42129e") }

Updated on: 11-May-2020

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements