英文:
MongoDB - Combination of Logical query operators not working as expected
问题
第二个文档不满足条件,但仍然包含在结果中。如何正确查询以排除第二个文档?
英文:
I am trying to filter data based on multiple conditions using Collection.find({...})
method but the output is not as expected, where userid = 6497cda5517300ca6a7e9767
.
{
$and: [
{
$or: [
{ from: userid },
{ to: userid },
],
},
{
$not: {
$and: [
{ to: userid },
{ status: "YOUR_TURN" },
],
},
},
],
}
Output :
[
{
from: new ObjectId("6497cc25517300ca6a7e973f"),
to: new ObjectId("6497cda5517300ca6a7e9767"),
status: 'COMPLETED',
},
{
from: new ObjectId("6497cc25517300ca6a7e973f"),
to: new ObjectId("6497cda5517300ca6a7e9767"),
status: 'YOUR_TURN',
},
{
from: new ObjectId("6497cda5517300ca6a7e9767"),
to: new ObjectId("6497cc25517300ca6a7e973f"),
status: 'WAITING',
}
]
The 2nd document does not satisfy the condition but still include in the result. What is the correct query to exclude 2nd doc?
答案1
得分: 1
以下是翻译好的部分:
"query failed: (BadValue) unknown top level operator: $not. If you are trying to negate an entire expression, use $nor."
翻译:查询失败:(BadValue)未知的顶级运算符:$not。如果您要否定整个表达式,请使用$nor。
"Replace $not
with $nor
and provide the conditions in array"
翻译:将$not
替换为 $nor
并提供条件数组。
"Or you need the $expr
operator and change the query as below:"
翻译:或者您需要使用 $expr
运算符,并按如下方式更改查询:
"Demo Approach 1 @ Mongo Playground"
翻译:演示方法1 @ Mongo Playground
"Demo Approach 2 @ Mongo Playground"
翻译:演示方法2 @ Mongo Playground
英文:
Doubt that your current query is valid. You will get the error:
> query failed: (BadValue) unknown top level operator: $not. If you are trying to negate an entire expression, use $nor.
Either:
- Replace
$not
with$nor
and provide the conditions in array
db.collection.find({
$and: [
{
$or: [
{
from: ObjectId("6497cda5517300ca6a7e9767")
},
{
to: ObjectId("6497cda5517300ca6a7e9767")
}
]
},
{
$nor: [
{
$and: [
{
to: ObjectId("6497cda5517300ca6a7e9767")
},
{
status: "YOUR_TURN"
}
]
}
]
}
]
})
Demo Approach 1 @ Mongo Playground
Or you need the $expr
operator and change the query as below:
db.collection.find({
$expr: {
$and: [
{
$or: [
{
$eq: [
"$from",
ObjectId("6497cda5517300ca6a7e9767")
]
},
{
$eq: [
"$to",
ObjectId("6497cda5517300ca6a7e9767")
]
}
]
},
{
$not: {
$and: [
{
$eq: [
"$to",
ObjectId("6497cda5517300ca6a7e9767")
]
},
{
$eq: [
"$status",
"YOUR_TURN"
]
}
]
}
}
]
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论