在 MongoDB 表达式中使用 $exists [英] Using $exists in a MongoDB expression
问题描述
对于背景,如果我想比较两个字段,我不能使用以下语法(因为它比较的是文字字符串$lastName"而不是 $lastName 字段的内容):
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"} }
我必须使用这个:
"$match": { "$expr": { $ne : [ "$firstName", "$lastName" ] } }
如果我想测试一个字段是否存在,我必须使用第一种格式:
If I want to test that a field exists I must use the first format:
"$match": { "fullName": { "$exists": true } }
我认为以后一种格式表达 $exists 运算符的正确方法会引发错误:
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
这是否意味着至少在某些情况下无法组合这些操作?具体来说,假设我想查找 either $fullName $exists OR $firstName $ne $lastName 的文档.可以表达吗?
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?
推荐答案
您将需要使用 $or
逻辑运算符来执行此操作.
You will need to use the $or
logical operator to do this.
{
"$or": [
{
"$expr": {
"$ne": [
"$firstName",
"$lastName"
]
}
},
{
"fullName": {
"$exists": true
}
}
]
}
您上次查询失败,因为 mongod 认为 $exists
是您传递 $expr
运算符的表达式.
You last query failed because mongod thinks $exists
is the expression you are passing the the $expr
operator.
这篇关于在 MongoDB 表达式中使用 $exists的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!