问题
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