1

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?

chridam
  • 100,957
  • 23
  • 236
  • 235
Luis Costa
  • 330
  • 1
  • 14

1 Answers1

2

Done with the following pipeline object inside the $lookup stage

"pipeline": [
                { "$match":
                    { "$expr":
                        { "$and":
                            [
                                { "$eq": [ "$type", "prescription" ] },
                                { "$eq": [ "$value.patient",  "$$patient" ] }
                            ]
                        }
                    }
                }
            ]
Luis Costa
  • 330
  • 1
  • 14