问题描述
如果 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>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
}
}]
)
这篇关于比较两个对象数组并检查它们是否具有共同元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!