I need to filter documents according to the value of the last element of a nested array using find
The reason I need it with find
and not aggregation
is the fact that the endpoint I’m sending the query to handle it is using only find
. pretty weird but I gotta work with that at the moment.
I tried to use $arrayElemAt
which is what I’ve found so far to handle it with find
and I managed to get the first arrays value, but I can’t figure out how to select the ids array and to act according to innerName
value.
Any suggestions?
Working query for the first array:
db.collection.find({
$or: [
{
$expr: {
"$eq": [
{
"$arrayElemAt": [
"$matches.name",
-1
]
},
"match 5"
]
}
}
]
})
Mock data of the use case:
[
{
"matches": [
{
"name": "match 1",
"ids": [
{
"innerName": "12"
},
{
"innerName": "3"
}
]
}
]
},
{
"matches": [
{
"name": "match 5",
"ids": [
{
"innerName": "123"
},
{
"innerName": "1234"
}
]
},
{
"name": "match 5",
"ids": [
{
"innerName": "1"
},
{
"innerName": "1234"
},
]
},
]
}
]