A have a collection with objects each with an array of documents, I want to query for a specific single documents across all the arrays.
Currently to do this I am finding the document with the array which contains the document I'm looking for, then projecting for this specific document.
This approach seems like an inefficient work around because:
- It will always iterate across all values without the ability to exit early when the desired document is found.
- It seems as if it would be
O(2n)since it iterates across all values for the match then all values again for the projection. - Returned document is awkwardly formed.
Is there a better approach for this?
Live example: https://mongoplayground.net/p/WowuB-mZpPI
db.collection.aggregate([
{
"$match": {
"values.name": "delta"
}
},
{
"$project": {
"value": {
"$filter": {
"input": "$values",
"cond": {
"$eq": [
"$$this.name",
"delta"
]
}
}
}
}
}
])
Example collection:
[
{
"group_name": "first",
"members": [
{
"name": "alpha",
"value": 1
},
{
"name": "beta",
"value": 2
},
{
"name": "gamma",
"value": 3
},
]
},
{
"group_name": "second",
"values": [
{
"name": "delta",
"value": 4
},
{
"name": "epsilon",
"value": 5
},
{
"name": "zeta",
"value": 6
},
]
}
]