Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7684

MongoDB aggregation project different fields based on the matched condition?

I am writing a query in MongoDB using aggregation such that if condition 1 matches then I want to project some fields and when condition 2 matches I want to project some different fields and when the third condition 3 reaches I want to project some other different fields.

My Query is like below

{
    $match: {
        $and: [
            {
                {field_a: "henesa"}
            },
            {
                $expr: {
                    $or: [
                        { Condition 1}, {Condition 2}, {condition 3}
                    ]
                }
            }
        ]

    }
},
{$project: { /* Here How To Decide which params to send */}}

Can anyone please tell me how can I do that.

Upvotes: 1

Views: 1031

Answers (1)

Alex Blex
Alex Blex

Reputation: 37098

You can use <field>: <expression> syntax of $projection at the projection stage.

In <expression> part you can use conditional operators to project values based on your criteria. E.g.

{ $project: {
    field: { $switch: {
        branches: [
             { case: Condition 1, then: "$field1" },
             { case: Condition 2, then: "$field2" },
             ...
        ]
    } }
} }

Or more complex combination of $cond if you need to handle cases when more than one $or conditions met.

Upvotes: 3

Related Questions