python - 在与 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,...]
在与查询相同的步骤中接收以保存运行时?此外,我无法更改集合的数量或格式。
解决方案
也许是这样的:
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 包含数组中的所有关联列表
- $reduce 并应用 concatArrays 以形成所有 AssociatedList 数组的单个数组总和
推荐阅读
- dart - 图片被上传多次而不是一次
- unity3d - 如何使用运动控制器移动对象
- mongodb - 无法连接到 Mongo atlas spring boot
- wordpress - 需要通过网络共享分类法所有站点
- java - 我如何从 MainActivity 的弹出登录转到另一个活动
- javascript - 比较两个数组并相应地更改属性
- c - 在 C 中使用 ' vs " 会发生什么?
- python - 根据现有数据框的条件创建一个新的数据框
- jquery-select2 - 如何使用 AJAX 预加载 select2 插件?
- sql-server - MSSQL:带有链接服务器的事务隔离级别