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.

Updated on: 2026-03-15T00:20:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements