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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With