Mongo 3.6 aggregation lookup with multiple conditions

匿名 (未验证) 提交于 2019-12-03 01:06:02

问题:

Suppose I have a Mongo DB with only one collection data. In this collection, I have the following documents:

{     "type": "person",     "value": {         "id": 1,         "name": "Person 1",         "age": 10     } }, {     "type": "person",     "value": {         "id": 2,         "name": "Person 2",         "age": 20     } }, {     "type": "prescription",     "value": {         "drug": "Bromhexine",         "patient": 2     } }, {     "type": "prescription",     "value": {         "drug": "Aspirin",         "patient": 1     } } 

With those records, I'd like to make a JOIN between documents with "type": person and "type": prescription on value.id = value.patient.

I've already tried an aggregation with the following stages:

{     "$match": {         "type": "person"     } }, {     "$lookup": {         "from": "data",         "let": { "patient": "$value.id"},         "pipeline": [             {                 "$match": {                     "$expr": {                         "type": "prescription",                         "value.patient": "$$patient"                     }                 }             }         ],         "as": "prescription"     } } 

But it produces an error FieldPath field names may not contain '.'. Which I believe is due to the "let": { "patient": "$value.id"}, line. If instead I try double dollar signs ($$) (as seen here), the result is the error Use of undefined variable: value.

Any idea of how I can make this aggregation?

回答1:

Done with the following pipeline object inside the $lookup stage

"pipeline": [                 { "$match":                     { "$expr":                         { "$and":                             [                                 { "$eq": [ "$type", "prescription" ] },                                 { "$eq": [ "$value.patient",  "$$patient" ] }                             ]                         }                     }                 }             ] 


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