首页 > 解决方案 > 与锚列相交多个集合行

问题描述

我有 N 个不同大小的集合,例如Collection 1Collection 2. 有没有一种有效的方法可以通过以下方式保持具有相同sourceid 值的行以及相应的targetid?

--Collection 1
`source` `target_1`
34        5
45        9
22        2
22        7     <--- not unique source id



--Collection 2
`source` `target_2`
34        23
25        9
22        8
17        99


--Result
`source` `target_1` `target_2`
34        5          23
22        2          8
22        7          8

编辑1:

到目前为止我所拥有的是

pipeline = [{'$lookup': {'from': 'Collection 2', 'localField': 'source', 'foreignField': 'source', 'as': 'source'}}]
for doc in (db['Collection 1'].aggregate(pipeline)): 
    print(doc)

我正在进入我的数据集,

{'_id': ObjectId('someCode'), 'source': [], 'target_1': 520838}
{'_id': ObjectId('someCode'), 'source': [{'_id': ObjectId('someCode'), 'target_2': 62483, 'source': 38758}, {'_id': ObjectId('someCode'), 'target_1': 62483, 'source': 38758}], 'target_1': 68099}

请有任何建议来改进查询以便获得示例中给出的行为?

编辑2:

评论后@AlexBlex我有

pipeline = [{'$lookup': {'from': 'Collection 2', 'localField': 'source', 'foreignField': 'source', 'as': 'source'}},{'$project': {"aligned._id": 0, "aligned.en": 0}]
    for doc in (db['Collection 1'].aggregate(pipeline)): 
        print(doc)

返回

{'_id': ObjectId('somecode'), 'source': 38758, 'target_1': 68099, 'aligned': {'target_2': 62483}}

我们可以进一步去除aligned标签以获得

{'_id': ObjectId('somecode'), 'source': 38758, 'target_1': 68099, 'target_2': 62483}

编辑3:

评论后@AlexBlex我有

pipeline = [{'$lookup': {'from': 'Collection 2', 'localField': 'source', 'foreignField': 'source', 'as': 'source'}},{"$project": {'source': 1, 'target_1': 1, 'target_2': "$aligned.target_2"}]
    for doc in (db['Collection 1'].aggregate(pipeline)): 
        print(doc)

返回

{'_id': ObjectId('somecode'), 'source': 9770, 'target_1': 4802, 'target_2': 180}
{'_id': ObjectId('somecode'), 'source': 9770, 'target_1': 4802, 'target_2': 180}
{'_id': ObjectId('somecode'), 'source': 9770, 'target_1': 4802, 'target_2': 180}
{'_id': ObjectId('somecode'), 'source': 9770, 'target_1': 4802, 'target_2': 5689}
{'_id': ObjectId('somecode'), 'source': 124, 'target_1': 78, 'target_2': 250}
{'_id': ObjectId('somecode'), 'source': 124, 'target_1': 78, 'target_2': 250}
{'_id': ObjectId('somecode'), 'source': 124, 'target_1': 78, 'target_2': 250}

标签: pythonmongodbmongodb-querypymongo

解决方案


推荐阅读