2

I'm trying to do the following in a mongo pipeline -

{ $project: { 
    newAttribute: { 
        $cond: [
            { $exists: { '$myAttribute': true } }, 
            1, 
            0
        ]
    }
}}

However this throws an error -

    Error: command failed: {
    "errmsg" : "exception: invalid operator '$exists'",
    "code" : 15999,
    "ok" : 0
}

I can see someone trying to do something similar here, but $ifNull doesn't help me because I want the value 1, rather than the value of the myAttribute field.

Is there a nice way to solve this?

Community
  • 1
  • 1
Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88

1 Answers1

3

You can use $allElementsTrue or $anyElementTrue if your MongoDB server version is 3.2 or newer like this:

db.collection.aggregate([
    { "$project": { 
        "newAttribute": { 
            "$cond": [
                { "$anyElementTrue": [ [ "$myAttribute" ] ] }, 
                1, 
                0
            ]
        }
    }}
])

From MongoDB version <= 3.0 you can always rely on the $ifNull operator to check if the field exists then use the $cond operator to set the value accordingly.

db.collection.aggregate([
    { "$project": { 
        "newAttribute": { 
            "$cond": [ 
                { "$eq": [ 
                    { "$ifNull": [ "$myAttribute", 99999 ] }, 
                    99999
                ]}, 
                0, 
                1
            ]
        }
    }}
])
styvane
  • 59,869
  • 19
  • 150
  • 156