How to convert ObjectId to string in MongoDB

MongoDBDatabaseBig Data Analytics

To convert ObjectId to string, use the $toString in MongoDB. To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.objectidToStringDemo.insertOne({"UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b80036de59bd9de0639d")
}
> db.objectidToStringDemo.insertOne({"UserName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b80436de59bd9de0639e")
}
> db.objectidToStringDemo.insertOne({"UserName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b80936de59bd9de0639f")
}
> db.objectidToStringDemo.insertOne({"UserName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b81836de59bd9de063a0")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.objectidToStringDemo.find().pretty();

The following is the output −

{ "_id" : ObjectId("5c92b80036de59bd9de0639d"), "UserName" : "John" }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e"), "UserName" : "Chris" }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0"), "UserName" : "Robert" }

Here is the query to convert ObjectId to the string value in MongoDB aggregate. The query is as follows −

> db.objectidToStringDemo.aggregate([
   ... {
      ... $project: {
         ... _id: {
            ... $toString: "$_id"
         ... }
      ... }
   ... }
... ]
... );

The following is the output −

{ "_id" : "5c92b80036de59bd9de0639d" }
{ "_id" : "5c92b80436de59bd9de0639e" }
{ "_id" : "5c92b80936de59bd9de0639f" }
{ "_id" : "5c92b81836de59bd9de063a0" }
raja
Published on 01-Apr-2019 11:44:12
Advertisements