Richard Jebasingh S
Richard Jebasingh S

Reputation: 23

How to use $cond in mongoDB without an else expression?

I want to add the values of $site to a variable if site!= 'undefined', else I have to skip that document and move on to the next.

I used

{$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site"}}}

But it returns "Missing 'else' parameter to $cond"

and if I add an else statement

1) {$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site", else: {} }}}

it returns the value to the addset {Object Object}

2) {$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site", else: null }}}

it returns null to the set like ["sample1", "sample2", ]

3) {$addToSet: { $cond: { if: { $ne: [ "$site", 'undefined' ] }, then: "$site", else: "" }}}

it returns null to the set like ["sample1", "sample2", "" ]

I don't want anything to be added to the set if it does not satisfy the condition.

Upvotes: 2

Views: 8650

Answers (2)

Sarath S Menon
Sarath S Menon

Reputation: 2331

Starting in MongoDB 3.6, you can use the $$REMOVE variable as the ELSE argument of a $cond operator to prevent anything from being added to the set if the condition fails.

See here for an example from Mongo Docs.

In your case, we can get it done with,

{
    $group: {
            //_id: <group-by-expression>
            // other fields (if any)..
            sites: {
                $addToSet: { 
                    $cond: {
                        if: { $ne: ["$site", 'undefined'] },
                        then: "$site",
                        else: "$$REMOVE"
                    }
                }
            }
    }
}

OR

{
    $group: {
            //_id: <group-by-expression>
            // other fields (if any)..
            sites: {
                $addToSet: { 
                    $cond: [
                        { $ne: ["$site", 'undefined'] },
                        "$site",
                        "$$REMOVE"
                    ]
                }
            }
    }
}

Upvotes: 8

Alexandru Martin
Alexandru Martin

Reputation: 236

You can add null on else brach(I used the simpliefied cond see here):

{
    $group: {
        _id: null,
            A: {
            $addToSet: {
                $cond: [{ $ne: ["$site", 'undefined'] }, "$site", null]
            }
        }
    }
}

and then:

{
    "$project": {
        "A": {
            "$setDifferrence": ["$A", [null]]
        },
    }
}

Upvotes: 2

Related Questions