Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $exists in a MongoDB expression

For background, if I want to compare two fields, I can't use the following syntax (because it compares to the literal string "$lastName" rather than the contents of the $lastName field):

"$match": { "firstName": { $ne : "$lastName"} }

I have to use this:

"$match": { "$expr": { $ne : [ "$firstName", "$lastName" ] } }

If I want to test that a field exists I must use the first format:

"$match": { "fullName": { "$exists": true } }

What I think would be the correct way for expressing the $exists operator in the latter format throws an error:

db.docs.aggregate([
  {
    "$match": { "$expr": { "$exists": [ "$fullName", true ] } }
  }
])
assert: command failed: {
        "ok" : 0,
        "errmsg" : "Unrecognized expression '$exists'",
        "code" : 168,
        "codeName" : "InvalidPipelineOperator"
} : aggregate failed

Does this mean it is not possible to combine these operations, at least in some conditions? Specifically, suppose I want to find docs where either $fullName $exists OR $firstName $ne $lastName. Can that be expressed?

like image 814
Paul Jackson Avatar asked Jul 12 '18 17:07

Paul Jackson


1 Answers

You will need to use the $or logical operator to do this.

{
   "$or": [
      {
         "$expr": {
            "$ne": [
               "$firstName",
               "$lastName"
            ]
         }
      },
      {
         "fullName": {
            "$exists": true
         }
      }
   ]
}

You last query failed because mongod thinks $exists is the expression you are passing the the $expr operator.

like image 155
styvane Avatar answered Sep 30 '22 03:09

styvane