在 mongoDB 中使用 $elemMatch 查询 $in [英] $in query with $elemMatch in mongoDB
问题描述
我需要找到一个文档,其中组件"不存在或如果存在,则其 ID 为 1111 且 isActive 为真且问题"不存在或其 ID 为 1111 且 isActive 为真.
I need to find a document where "components" not exist OR if exists, its id is 1111 and isActive is true and "issues" not exist OR its id is 1111 and isActive is true.
示例:文档 1:////这包含组件"但不包含问题"
Example: Document 1: ////this contains "components" but not "issues"
{..
"components" : [
{
"id" : "1111",
"name" : "component1",
"isActive" : true
}
],
}
文档 2://this 包含问题"但不包含组件"
Document 2://this contains "issues" but not "components"
{..
"issues" : [
{
"id" : "1111",
"name" : "issue 1",
"isActive" : true
}
],
..}
文档 3://这两个都没有
Document 3://This is not having both
查询:
db.sample.find({
"issues":{$in:[null, {"$elemMatch" : {"id":"1111","isActive": {"$in":[true,null]}}}]},
"components":{$in:[null, {"$elemMatch" : {"id":"1111","isActive": {"$in":[true,null]}}}]}
})
但我收到一个错误,errmsg":不能在 $in 下嵌套 $",
But I am getting an error, "errmsg" : "cannot nest $ under $in",
请帮助形成返回所有上述 3 个文档的查询.
Please help to form the query that returns all the above 3 documents.
推荐答案
您不需要 $in
.您需要 $or
运算符.
You don't require $in
. You need $or
operator.
试试
db.sample.find({
$or:[
{"issues":{$exists:true,"$elemMatch" : {"id":"1111","isActive": true}}},
{"components":{$exists:true,"$elemMatch" : {"id":"1111","isActive": true}}}
]
})
基于 OP 的评论.这是工作版本.
Based on OP's comments. here is the working version.
db.Sample.find({
$or:[
{"issues":{$exists:true,"$elemMatch":{"id":"1111","isActive":true}},
"components":{$exists:false} },
{"components":{$exists:true,"$elemMatch":{"id":"1111","isActive":true}},
"issues":{$exists:false}},
{"issues":{$exists:true,"$elemMatch":{"id":"1111","isActive": true}},
"components":{$exists:true,"$elemMatch":{"id":"1111","isActive":true}}},
{"issues":{$exists:false}, "components":{$exists:false}}
]
})
这篇关于在 mongoDB 中使用 $elemMatch 查询 $in的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!