可能是这样的:
mongos> db.k1.find() // collection 1
{ "_id" : ObjectId("601fdf2698e4dc7a4ba5abb4"), "id" : 1, "theAssociatedList" : [ "A1", "A2", "A3" ] }
{ "_id" : ObjectId("601fdf3e98e4dc7a4ba5abb5"), "id" : 2, "theAssociatedList" : [ "A5", "A6", "A7" ] }
mongos> db.k2.find() // collection 2
{ "_id" : ObjectId("601fdf5198e4dc7a4ba5abb6"), "id" : 1, "theAssociatedList" : [ "B1", "B2", "B3" ] }
{ "_id" : ObjectId("601fdf5e98e4dc7a4ba5abb7"), "id" : 2, "theAssociatedList" : [ "B6", "B7", "B8" ] }
mongos> db.k3.find() // collection 3
{ "_id" : ObjectId("601fdf7498e4dc7a4ba5abb8"), "id" : 1, "theAssociatedList" : [ "C1", "C2", "C3" ] }
mongos> db.k1.aggregate([
{$match:{id:1} },
{ $unionWith:{coll:"k2",pipeline:[ {$match:{id:1}} ] }},
{ $unionWith:{coll:"k3",pipeline:[ {$match:{id:1}} ] }},
{$group:{_id:"$id" , a:{ $addToSet:"$theAssociatedList" }}},
{$project:{theAssociatedList:{$reduce:{input:"$a",initialValue:[] , in:{$concatArrays:["$$value" ,"$$this"] } }}}} ])
{ "_id" : 1, "theAssociatedList" : [ "B1", "B2", "B3", "A1", "A2", "A3", "C1", "C2", "C3" ] }
mongos>
解释:
- 从第一个集合中过滤 id=1
- $unionWith id=1 来自第二个集合 ($unionWith = SQL UNION ALL)
- $unionWith 来自第三个集合,id=1
- $group 基于 id 组成新元素 a,包含数组中的所有 AssosciatedList
- $reduce 并应用 concatArrays 以形成所有 AssociatedList 数组的单个数组总和