Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-lookup

$lookup with two $concat fields


Given those documents:

{
    "name" : "User",
    "class" : "clazz",
    "reference" : "ref"
}

{
    "classReference" : "clazz+ref",
    "room" : "123"
}

How can I do a $lookup to retrieve a document like this (without changing the documents):

{
    "name" : "User",
    "class" : "clazz",
    "reference" : "ref",
    "classReference" : "clazz+ref",
    "room" : "123"
}

Solution

  • You can use below aggregation with mongodb 3.6 and above

    db.user.aggregate([
      { "$lookup": {
        "from": Room.collection.name,
        "let": { "ref": { "$concat": ["$class", "$reference"] } },
        "pipeline": [
          { "$match": { "$expr": { "$eq": ["$classReference", "$$ref"] } } }
        ],
        "as": "ref"
      }},
      { "$project": {
        "classReference": { "$arrayElemAt": ["$ref.classReference", 0] },
        "room": { "$arrayElemAt": ["$ref.room", 0] },
        "name": 1,
        "class": 1
        "reference": 1
      }}
    ])
    

    Basically you need to $concat both the class and reference and then pass it to $lookup pipeline.