首页 > 解决方案 > 在与 mongodb 中的查询相同的步骤中组合查询结果?

问题描述

我有 3 个 mongodb 集合,格式如下:

firstCollection = {
     "id":myId,
     "theAssociatedList":myList
}

secondCollection = {
      "id":myId,
      "theAssociatedList":myList
}

thirdCollection = {
      "id":myId,
      "theAssociatedList":myList
}

您可以通过提供一个 Id 来查询每个集合,该 Id 返回相应的列表作为结果。例如,

查询所有三个集合后,我收到列表[A1,A2,...,A3], [B1,B2,...,B3], and [C1,C2,...,C3]作为输出。如何[A1,B1,C1,A2,B2,C2,A3,B3,C3,...]在与查询相同的步骤中接收以保存运行时?此外,我无法更改集合的数量或格式。

标签: pythonpython-3.xdatabasemongodblogic

解决方案


也许是这样的:

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> 

解释:

  1. 从第一个集合中过滤 id=1
  2. $unionWith id=1 来自第二个集合( $unionWith = SQL UNION ALL )
  3. $unionWith id=1 来自第三个集合
  4. $group 基于 id 形成新元素 a 包含数组中的所有关联列表
  5. $reduce 并应用 concatArrays 以形成所有 AssociatedList 数组的单个数组总和

推荐阅读