问题描述
如果FirstArray
和SecondArray
在名称"字段中具有相同的元素,如何在MongoDB中执行返回_id的查询?
How can I execute a query in MongoDB that returns _id if FirstArray
and SecondArray
has elements in common in "Name" field?
这是集合结构:
{
"_id" : ObjectId("58b8d9e3b2b4e07bff8feed5"),
"FirstArray" : [
{
"Name" : "A",
"Something" : "200 ",
},
{
"Name" : "GF",
"Something" : "100 ",
}
],
"SecondArray" : [
{
"Name" : "BC",
"Something" : "200 ",
},
{
"Name" : "A",
"Something" : "100 ",
}
]
}
推荐答案
3.6更新:
将$match
与$expr
一起使用. $expr
允许在$match
阶段使用聚合表达式.
Use $match
with $expr
. $expr
allows use of aggregation expressions inside $match
stage.
db.collection.aggregate([
{"$match":{
"$expr":{
"$eq":[
{"$size":{"$setIntersection":["$FirstArray.Name","$SecondArray.Name"]}},
0
]
}
}},
{"$project":{"_id":1}}
])
旧版本:
您可以尝试将$redact
与$setIntersection
进行查询.
You can try $redact
with $setIntersection
for your query.
$setIntersection
将FirstArray
s Name
s与SecondArray
s Name
s进行比较,并返回紧随其后的$size
和$redact
的通用名称文档数组,并将结果与0
进行比较保留并删除文档.
$setIntersection
to compare the FirstArray
s Name
s with SecondArray
s Name
s and return array of common names documents followed by $size
and $redact
and compare result with 0
to keep and else remove the document.
db.collection.aggregate(
[{
$redact: {
$cond: {
if: {
$eq: [{
$size: {
$setIntersection: ["$FirstArray.Name", "$SecondArray.Name"]
}
}, 0]
},
then: "$$KEEP",
else: "$$PRUNE"
}
}
}, {
$project: {
_id: 1
}
}]
)
这篇关于比较两个对象数组并检查它们是否具有公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!