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.
{
"_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