Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB $lookup array of lookup field values

I’m using MongoDB, and I tried to do it with many pipeline steps but I couldn’t find a way.

I have a players collection, each player contains an items array

{
    "_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
    "username": "moshe",
    "items": [ 
        "5fbb5ab778045a985690b5fc",
        "5fbb5ab778045a985690b5fd"
    ]
}

I have an items collection where there is more information about each item in the player items array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "_id": ObjectId("5fbb5ab778045a985690b5fc"),
    "name": "Axe",
    "damage": 4,
    "defense": 6
}
{
    "_id": ObjectId("5fbb5ab778045a985690b5fd"),
    "name": "Demo",
    "damage": 1,
    "defense": 1
}

My goal is to have a player document with all the information about the item inside his items array, so it will look like that:

{
    "_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
    "username": "moshe",
    "items": [
        {
            "_id": ObjectId("5fbb5ac178045a985690b5fd"),
            "equipped": false,
            "itemId": "5fbb5ab778045a985690b5fc",
            "name": "Axe",
            "damage": 4,
            "defense": 6
        },
        {
            "_id": ObjectId("5fbb5ac178045a985690b5fa"),
            "equipped": false,
            "itemId": "5fbb5ab778045a985690b5fd",
            "name": "Demo",
            "damage": 1,
            "defense": 1
        }
    ]
}

>Solution :

One option is to use $lookup with a pipeline to overcome the difference between ObjectId and string:

db.players.aggregate([
  {$lookup: {
      from: "items",
      let: {items: "$items"},
      pipeline: [
        {$match: {$expr: {$in: [{$toString: "$_id"}, "$$items"]}}}
      ],
      as: "items"
    }
  }
])

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading