Concatenate with condition in MongoDB?

To concatenate with condition in MongoDB, use $cond with $concat in an aggregation pipeline. This allows you to perform string concatenation based on specific conditions and filter results accordingly.

Syntax

db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [{ "$concat": ["$field1", "$field2"] }, "targetValue"] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
]);

Sample Data

db.demo745.insertMany([
    { "Value1": "100", "Value2": "100" },
    { "Value1": "40", "Value2": "50" },
    { "Value1": "13", "Value2": "45" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5eae6419a930c785c834e554"),
        ObjectId("5eae6421a930c785c834e555"),
        ObjectId("5eae6429a930c785c834e556")
    ]
}

Display all documents from the collection ?

db.demo745.find();
{ "_id": ObjectId("5eae6419a930c785c834e554"), "Value1": "100", "Value2": "100" }
{ "_id": ObjectId("5eae6421a930c785c834e555"), "Value1": "40", "Value2": "50" }
{ "_id": ObjectId("5eae6429a930c785c834e556"), "Value1": "13", "Value2": "45" }

Example: Filter Documents by Concatenated Values

Find documents where concatenating Value1 and Value2 equals "1345" ?

db.demo745.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [{ "$concat": ["$Value1", "$Value2"] }, "1345"] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
]);
{ "_id": ObjectId("5eae6429a930c785c834e556"), "Value1": "13", "Value2": "45" }

How It Works

  • $concat combines Value1 and Value2 into a single string
  • $eq checks if the concatenated result equals the target value "1345"
  • $$KEEP includes the document if condition is true
  • $$PRUNE excludes the document if condition is false

Conclusion

Use $redact with $cond and $concat to filter documents based on concatenated field values. This approach efficiently combines string operations with conditional logic in MongoDB aggregation pipelines.

Updated on: 2026-03-15T03:55:00+05:30

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements