Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo - how to match on lookup?

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?

like image 552
Kevin Avatar asked Feb 02 '17 01:02

Kevin


1 Answers

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)
like image 91
Kevin Avatar answered Sep 22 '22 03:09

Kevin