python - 与锚列相交多个集合行
问题描述
我有 N 个不同大小的集合,例如Collection 1
和Collection 2
. 有没有一种有效的方法可以通过以下方式保持具有相同source
id 值的行以及相应的target
id?
--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}
解决方案
推荐阅读
- statistics - 我们如何比较同一调查的两个数据集(不同大小和来自两个不同的人群)。调查包含名义类别
- javascript - 问题不断重复
- ios - 使用 iOS 的不正确的特征长度
- html - 如何修改 Excel 的 VBA 代码以与 Access 表一起使用?
- html - 具有两个字段的可点击列表项:序列号和名称
- python - 如何使用 tkinter python 将变量设置为 text_areas 中的文本?
- c# - Auth0 WebApi asp.net 核心设置
- terraform - 在 IBM 云上运行 terraform 导入时出现 Terraform 崩溃错误
- java - 如何将 LocalDateTime 与 Hibernate 原始 sql 查询一起使用?
- java - javafx中代码区域的自动完成