第一个文档:
{
"_id" : 1,
"array" : [
{
"userID" : 1,
"name" : "name 1"
},
{
"userID" : 2,
"name" : "name 2"
},
{
"userID" : 3,
"name" : "name 3"
},
{
"userID" : 6,
"name" : "name 6"
}
]
}
第二个文档:
{
"_id" : 2,
"array" : [
{
"userID" : 1,
"name" : "name 1"
},
{
"userID" : 2,
"name" : "name 2"
},
{
"userID" : 3,
"name" : "name 3"
},
{
"userID" : 4,
"name" : "name 4"
},
{
"userID" : 5,
"name" : "name 5"
}
]
}
有什么办法可以得到这样的输出:
{
"array" : [
{
"userID" : 1,
"name" : "name 1"
},
{
"userID" : 2,
"name" : "name 2"
},
{
"userID" : 3,
"name" : "name 3"
}
]
}
我想比较两个文档的数组字段并检索其中的公共元素。并仅通过公用'userID'
比较数组字段。我们可以通过$setIntersection
来做到吗?我一次只需要检查两个数组字段。
答案 0 :(得分:1)
您可以使用$setIntersection
db.t67.aggregate([
//{$match : {}} add filter criteria to filter documents
{$group : {_id : null, array : {$push : "$array"}}},
{$project : {_id :0, array : {$reduce : {input : "$array", initialValue : {$arrayElemAt : ["$array", 0]}, in : {$setIntersection : ["$$this", "$$value"]}}}}}
])
输出
> db.t67.aggregate([
... {$group : {_id : null, array : {$push : "$array"}}},
... {$project : {_id :0, array : {$reduce : {input : "$array", initialValue : {$arrayElemAt : ["$array", 0]}, in : {$setIntersection : ["$$this", "$$value"]}}}}}
... ])
{ "array" : [ { "userID" : 1, "name" : "name 1" }, { "userID" : 2, "name" : "name 2" }, { "userID" : 3, "name" : "name 3" } ] }
或$unwind
和$group
db.t67.aggregate([
// $match stages to filter 2 documents
{$unwind : "$array"},
{$group : {_id : "$array", count : {$sum : 1}}},
{$match : {count : {$gt : 1}}},
{$project : {count : 0}},
{$group : {_id : null, array : {$push : "$_id"}}},
{$project : {_id : 0}}
])
输出
{ "_id" : null, "array" : [ { "userID" : 3, "name" : "name 3" }, { "userID" : 2, "name" : "name 2" }, { "userID" : 1, "name" : "name 1" } ] }