How to convert value to string using $toString in MongoDB?

MongoDBDatabaseBig Data Analytics

Let us see an example to understand 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 a 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" }

In order to get the original ObjectId, use the $toObjectId operator −

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

The following is the output −

{ "_id" : ObjectId("5c92b80036de59bd9de0639d") }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e") }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f") }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0") }
raja
Published on 01-Apr-2019 11:46:33
Advertisements