Tudor
Tudor

Reputation: 329

Why can't $cond (aggregation) take only two parameters to become a simple if-statement?

      count_wanted_group: {
            $sum: {
                $cond: [{
                    $and: [{
                        $eq: ["$status", "W"]
                    }]
                }, 1, null]
            }
        },

The problem is that I don't want to pass that null. It will generate me something equal to 0. I want it to generate nothing.

Many thanks!

Upvotes: 0

Views: 3232

Answers (2)

Sarath S Menon
Sarath S Menon

Reputation: 2331

The $cond aggregation operator requires all three arguments as mentioned in the MongoDB Docs.

There is a workaround for this issue, using the $$REMOVE variable, available since MongoDB 3.6. It allows for the conditional exclusion of fields. See here for an example from the Mongo reference manual.

For your question,

{
    $group: {
        // _id: <expression>, // Group By Expression
        count_wanted_group: {
            $sum: {
                $cond: [
                    { $eq: ["$status", "W"] },
                    1,
                    "$$REMOVE"
                ]
            }
        }
    }
}

Upvotes: 2

Neil Lunn
Neil Lunn

Reputation: 151112

I think you mean this:

{ "$group": {
    "_id": someKey,
    "count_wanted_group": {
        "$sum": {
            "$cond": [
                { "$eq": "$status", "W" },
                1,
                0
            ]
        }
    }
}}

The $cond operator is a "ternary" or "if..then..else" construct. You can combine as many logical operators as you want into the "condition" or "if" part such as $and and $or or anything that eventually evaluates to a true/false assertion.

It's the "then" an "else" parts that matter, and in this case you either want to present 1 as a value to the $sum operation when the condition is true or 0 to the "sum" when the condition is false.

That is generally how a "ternary" works.

Upvotes: 2

Related Questions