pymongo - how to match on lookup?

蓝咒 提交于 2019-12-22 10:59:32

问题


I have two collections, a model and a papers collection. I need to be able to match fields from both of them. They have a field in common called reference which contains an identifier.

I want to match documents that have the following

'authors' : 'Migliore M' from the papers collection 'celltypes' : 'Hippocampus CA3 pyramidal cell' from the models collection

Here is what my code looks like:

pipeline = [{'$lookup': 
                {'from' : 'models',
                 'localField' : 'references',
                 'foreignField' : 'references',
                 'as' : 'cellmodels'}},
             {'$match':
                 {'authors' : 'Migliore M', 'cellmodels.celltypes' : 'Hippocampus CA3 pyramidal cell'}},


             ]

for doc in (papers.aggregate(pipeline)):
    pprint (doc)

I get no results.

I notice that if I do not call on the cellmodels.celltypes in the match parameter it will find the papers that match Migliore M. How can I get it to also match the celltype:'Hippocampus CA3 pyramidal cell' from the models collection in this query?


回答1:


This worked:

pipeline = [{'$lookup': 
                {'from' : 'models',
                 'localField' : '_id',
                 'foreignField' : 'references',
                 'as' : 'cellmodels'}},
            {'$unwind': '$cellmodels'},
             {'$match':
                 {'authors' : 'Migliore M', 'cellmodels.celltypes' : 'Hippocampus CA3 pyramidal cell'}},
            {'$project': 
                {'authors':1, 'cellmodels.celltypes':1}} 
             ]

for doc in (papers.aggregate(pipeline)):
    pprint (doc)


来源:https://stackoverflow.com/questions/41992885/pymongo-how-to-match-on-lookup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!