14

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?

Paul Jackson
  • 2,077
  • 2
  • 19
  • 29
  • Possible dupe of https://stackoverflow.com/questions/25497150/mongodb-aggregate-by-field-exists – s7vr Jul 12 '18 at 17:27

2 Answers2

15

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.

styvane
  • 59,869
  • 19
  • 150
  • 156
  • This answer is what I was looking for, which is not addressed in https://stackoverflow.com/questions/25497150/mongodb-aggregate-by-field-exists, so my perspective is that it is not a duplicate, but I have a bias. Thanks for the answer. – Paul Jackson Jul 12 '18 at 18:57
  • Will this be indexed? – Iglesias Leonardo Aug 19 '22 at 20:08
1

{$ne: [{$type: "$field"}, "missing"]}

https://www.mongodb.com/docs/manual/reference/operator/aggregation/type/

  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Feb 15 '23 at 10:07
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 22 '23 at 11:14