【问题标题】:Combine query results in same step as query in mongodb?在与 mongodb 中的查询相同的步骤中组合查询结果?
【发布时间】:2021-02-07 06:23:29
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: python python-3.x database mongodb logic


    【解决方案1】:

    可能是这样的:

    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,包含数组中的所有 AssosciatedList
    5. $reduce 并应用 concatArrays 以形成所有 AssociatedList 数组的单个数组总和

    【讨论】:

    • 我没有对应的_id,我也相信你的语法是关闭的。应该有引号包裹至少 $match 和 $unionWith @R2D2
    猜你喜欢
    • 2017-01-14
    • 2016-11-18
    • 2014-11-25
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多