Replace value with a string literal during MongoDB aggregation operation

Use MongoDB $literal operator in aggregation pipelines to replace field values with fixed string constants during projection operations. The $literal operator treats its value as a literal value, preventing MongoDB from interpreting it as a field reference or expression.

Syntax

db.collection.aggregate([
    {
        $project: {
            fieldName: { $literal: "string_value" }
        }
    }
]);

Sample Data

Let us first create a collection with documents ?

db.replacevaluedemo.insertMany([
    {
        "StudentName": "Chris",
        "StudentFavouriteSubject": {
            "TeacherName": "Bob",
            "SubjectCode": "MySQL111"
        }
    },
    {
        "StudentName": "Mike",
        "StudentFavouriteSubject": {
            "TeacherName": "David",
            "SubjectCode": "3221Java"
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e0390a3f5e889d7a51994fd"),
        ObjectId("5e0390b8f5e889d7a51994fe")
    ]
}

Display all documents from the collection ?

db.replacevaluedemo.find().pretty();
{
    "_id": ObjectId("5e0390a3f5e889d7a51994fd"),
    "StudentName": "Chris",
    "StudentFavouriteSubject": {
        "TeacherName": "Bob",
        "SubjectCode": "MySQL111"
    }
}
{
    "_id": ObjectId("5e0390b8f5e889d7a51994fe"),
    "StudentName": "Mike",
    "StudentFavouriteSubject": {
        "TeacherName": "David",
        "SubjectCode": "3221Java"
    }
}

Example: Replace Teacher Name with String Literal

Replace all teacher names with the literal string "UNKNOWN NAME" while preserving subject codes ?

db.replacevaluedemo.aggregate([
    {
        "$project": {
            "_id": 1,
            "StudentFavouriteSubject": {
                "SubjectCode": "$StudentFavouriteSubject.SubjectCode",
                "TeacherName": { $literal: "UNKNOWN NAME" }
            }
        }
    }
]);
{
    "_id": ObjectId("5e0390a3f5e889d7a51994fd"),
    "StudentFavouriteSubject": {
        "SubjectCode": "MySQL111",
        "TeacherName": "UNKNOWN NAME"
    }
}
{
    "_id": ObjectId("5e0390b8f5e889d7a51994fe"),
    "StudentFavouriteSubject": {
        "SubjectCode": "3221Java",
        "TeacherName": "UNKNOWN NAME"
    }
}

Key Points

  • $literal ensures the value is treated as a constant, not a field reference
  • Useful for replacing sensitive data or creating uniform placeholder values
  • Can be combined with other projection operations in the same $project stage

Conclusion

The $literal operator provides a reliable way to replace field values with fixed strings during aggregation. This is particularly useful for data masking or standardizing output values across documents.

Updated on: 2026-03-15T01:46:48+05:30

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements