首页 > 解决方案 > 多个集合中的聚合查询 Mongodb (pymongo)

问题描述

我想在多个集合中应用聚合查询。我有以下集合,每个集合中都有一个字段partner,我想从partner 包含的所有集合中过滤掉john,这是我的集合 -

公司

{
    'com_id': 121,
    'name': 'abc',
    'pin': 45009,
    'partner': ['john', 'mack', 'michel'],
    'type': 'company'
}

风险投资

{
    'ven_id': 342,
    'type': 'real_estate',
    'partner': ['john', 'duke', 'michel']
}

财产

{
    'prop_id': 213,
    'address': 'xyz',
    'partner': ['john', 'gore', 'tiger'],   
    'type': 'property'
}

并希望得到预期的结果——

[
{'type': 'company', 'id': 121, 'name': 'john'},
{'type': 'real_estate', 'id': 342, 'name': 'john'},
{'type': 'property', 'id': 213, 'name': 'john'}
]

这是我尝试过的,但对我不起作用。

mydb.company.aggregate([
        {'$match': {'partner': {'$in': ['john']}}},
        {'$lookup': {'from': "ventures", 'localField': "partner", 'foreignField': "partner", 'as': "final_data"}},
        {'$lookup': {'from': "property", 'localField': "partner", 'foreignField': "partner", 'as': "final_data"}},
])

标签: pythonmongodbmongodb-queryaggregation-frameworkpymongo

解决方案


推荐阅读