Consider the following dataset:
lists
{ _id: 1, included_lists: [ 2 ], items: [ "i1" ]}
{ _id: 2, included_lists: [], items: [ "i2", "i3" ]}
items
{ _id: "i1", details: [{}, {}, {}]}
{ _id: "i2", details: [{}, {}, {}]}
{ _id: "i3", details: [{}, {}, {}]}
I am trying to retrieve all the items for a list, including those attached to the included_lists
For instance, if we are examining list with _id
1, we should get items i1, i2, i3
My approach involves using populate
or $lookup
, but I'm uncertain about how to unwind the nested items
inside the included_lists
and connect them with the original list's items
.
Ultimately, I want to work with a dataset where I can utilize limit
, skip
, and match
.
I am utilizing mongoose, however raw mongodb code would also suffice.
Update
My current strategy is to first fetch all the list ids in one query like so:
List.find({ _id: id}, { included_lists: 1})
Then, create an array of all those ids:
var all_ids = [id, ...included_lists]
Subsequently, find the items and unwind them
Pseudo-code:
List
.aggregate([
{
$match: {
_id: {
$in: all_ids
}
}
},
{ $lookup: {} }
{
$unwind: "$items"
},
{
$project: {
"list.name": 1,
"list._id": 1,
"items": 1
}
}
])
However, I wish to avoid having to execute an initial query to retrieve all the list_ids, rather I should be able to fetch all related items through just one _id
which will then enable me to access the remaining items via included_lists