In my collection, I have a variety of documents that look like this:
[{
id: 1,
name: 'My document 1',
allItems: [{
id: 'item1',
name: 'My item 1'
}, {
id: 'item2',
name: 'My item 2'
}, {
id: 'item3',
name: 'My item 3'
}],
containers: [{
id: 'container1',
selectedItems: [
'item3',
'item1'
]
}, {
id: 'container2',
selectedItems: [
'item3'
]
}]
},
...]
Now, I am tasked with writing a query to extract a specific document based on its container ID (e.g. container1
). The goal is to return the document while updating the selectedItems
array to display the corresponding values from the allItems
array within the same document.
The desired output should resemble this:
{
id: 1,
name: 'My document 1',
container: {
id: 'container1',
selectedItems: [{
id: 'item3',
name: 'My item 3'
}, {
id: 'item1',
name: 'My item 1'
}
}
}
In my current Node.js aggregation setup, I have implemented the following logic:
db.collection.aggregate([{
$match: {'containers.id': 'container1'},
$addFields: {
container: {
$filter: {
input: '$containers',
as: 'container',
cond: {
$eq: ['$$container.id', 'container1']
}
}
}
},
$project: {containers: 0},
$unwind: {path: '$container'}
// At this stage, the "container" property contains the correct subdocument from the array
// and the original array with all containers has been removed.
// Next, a step is needed to populate the container subdocuments in the `selectedItems` array
$project: {allItems: 0} // Remove the list of all items when no longer necessary for future steps
}]);
I am aware of the existence of $lookup
, but given that I want to fill out the matching array items from the same document (rather than a different collection), I believe it may not be required. Even if I were to specify the same collection in a $lookup
, it would populate the array with the root document of my collection, potentially leading to complexity when unwinding & matching the required properties of the subdocument.
One option I considered was creating a separate items
collection, but this could result in slower lookups and unnecessary relational data for my particular dataset.
I trust that my query is clear, and I am grateful for any assistance provided!
While additional transformations are being applied to my real data, such as copying certain properties from the original root document and concealing others, these details should not impact the core question at hand.
Thank you once again!