Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert value to string using $toString in MongoDB?
The $toString operator in MongoDB converts any value to its string representation within aggregation pipelines. It's particularly useful for converting ObjectId values, numbers, or dates to strings for display, comparison, or data transformation purposes.
Syntax
{
$project: {
fieldName: { $toString: "$fieldToConvert" }
}
}
Sample Data
db.objectidToStringDemo.insertMany([
{"UserName": "John"},
{"UserName": "Chris"},
{"UserName": "Larry"},
{"UserName": "Robert"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c92b80036de59bd9de0639d"),
ObjectId("5c92b80436de59bd9de0639e"),
ObjectId("5c92b80936de59bd9de0639f"),
ObjectId("5c92b81836de59bd9de063a0")
]
}
Display all documents from the collection ?
db.objectidToStringDemo.find().pretty();
{ "_id": ObjectId("5c92b80036de59bd9de0639d"), "UserName": "John" }
{ "_id": ObjectId("5c92b80436de59bd9de0639e"), "UserName": "Chris" }
{ "_id": ObjectId("5c92b80936de59bd9de0639f"), "UserName": "Larry" }
{ "_id": ObjectId("5c92b81836de59bd9de063a0"), "UserName": "Robert" }
Example: Convert ObjectId to String
db.objectidToStringDemo.aggregate([
{
$project: {
_id: {
$toString: "$_id"
},
UserName: 1
}
}
]);
{ "_id": "5c92b80036de59bd9de0639d", "UserName": "John" }
{ "_id": "5c92b80436de59bd9de0639e", "UserName": "Chris" }
{ "_id": "5c92b80936de59bd9de0639f", "UserName": "Larry" }
{ "_id": "5c92b81836de59bd9de063a0", "UserName": "Robert" }
Reversing with $toObjectId
To convert the string back to ObjectId, use $toObjectId operator ?
db.objectidToStringDemo.aggregate([
{
$project: {
_id: {
$toObjectId: "$_id"
}
}
}
]);
{ "_id": ObjectId("5c92b80036de59bd9de0639d") }
{ "_id": ObjectId("5c92b80436de59bd9de0639e") }
{ "_id": ObjectId("5c92b80936de59bd9de0639f") }
{ "_id": ObjectId("5c92b81836de59bd9de063a0") }
Conclusion
The $toString operator provides an efficient way to convert ObjectId and other data types to string format within aggregation pipelines. Use $toObjectId to reverse the conversion when needed.
Advertisements
