- 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
How to convert value to string using $toString in MongoDB?
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") }
Advertisements