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 ObjectId to string in MongoDB
To convert ObjectId to string in MongoDB, use the $toString operator within an aggregation pipeline. This converts the ObjectId value to its string representation.
Syntax
db.collection.aggregate([
{
$project: {
_id: { $toString: "$_id" },
// other fields as needed
}
}
]);
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 Sample Documents
db.objectidToStringDemo.find().pretty();
{ "_id": ObjectId("5c92b80036de59bd9de0639d"), "UserName": "John" }
{ "_id": ObjectId("5c92b80436de59bd9de0639e"), "UserName": "Chris" }
{ "_id": ObjectId("5c92b80936de59bd9de0639f"), "UserName": "Larry" }
{ "_id": ObjectId("5c92b81836de59bd9de063a0"), "UserName": "Robert" }
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" }
Key Points
-
$toStringonly works within aggregation pipelines, not in regular find() queries. - Include other fields with
fieldName: 1in the $project stage to preserve them. - The converted string maintains the same hexadecimal value as the original ObjectId.
Conclusion
Use $toString in an aggregation $project stage to convert ObjectId fields to string format. This is useful for data export, API responses, or string-based operations on ObjectId values.
Advertisements
