MongoDB query to push a computed expression in a $group?

To push a computed expression in MongoDB's $group stage, use the $push operator combined with conditional expressions like $cond. This allows you to transform field values during the grouping process and collect them into arrays.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: "$fieldName",
            arrayField: {
                $push: {
                    $cond: [
                        { $eq: ["$field", value] },
                        "trueValue",
                        "falseValue"
                    ]
                }
            }
        }
    }
])

Sample Data

db.demo24.insertMany([
    { "Id": 100, "Status": true },
    { "Id": 100, "Status": true },
    { "Id": 100, "Status": false },
    { "Id": 100, "Status": true },
    { "Id": 100, "Status": false }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e14c58722d07d3b95082e72"),
        ObjectId("5e14c58a22d07d3b95082e73"),
        ObjectId("5e14c58f22d07d3b95082e74"),
        ObjectId("5e14c59122d07d3b95082e75"),
        ObjectId("5e14c59222d07d3b95082e76")
    ]
}

Display all documents from the collection ?

db.demo24.find();
{ "_id": ObjectId("5e14c58722d07d3b95082e72"), "Id": 100, "Status": true }
{ "_id": ObjectId("5e14c58a22d07d3b95082e73"), "Id": 100, "Status": true }
{ "_id": ObjectId("5e14c58f22d07d3b95082e74"), "Id": 100, "Status": false }
{ "_id": ObjectId("5e14c59122d07d3b95082e75"), "Id": 100, "Status": true }
{ "_id": ObjectId("5e14c59222d07d3b95082e76"), "Id": 100, "Status": false }

Example: Push Computed Expression

Group by Id and push computed values based on Status field ?

db.demo24.aggregate([
    {
        $group: {
            _id: "$Id",
            AllValues: {
                $push: {
                    $cond: [
                        { $eq: ["$Status", true] },
                        "Active",
                        "InActive"
                    ]
                }
            }
        }
    }
]);
{ "_id": 100, "AllValues": ["Active", "Active", "InActive", "Active", "InActive"] }

How It Works

  • $group: Groups documents by the specified field (Id in this case)
  • $push: Adds computed values to an array for each group
  • $cond: Conditional expression that evaluates Status and returns "Active" for true, "InActive" for false

Conclusion

The $push operator with $cond in $group enables you to transform and collect field values into arrays during aggregation. This pattern is useful for creating computed summaries of grouped data.

Updated on: 2026-03-15T02:38:22+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements