How query on the last element of array?
ej:
{
name:"Peter Parker",
friends: [
{name:"tony stark"},
{name:"wolverine"}
]
}
I can search the first element with - collection.find({friends.0.name:'wolverine'})
but the last?
collection.find({friends.$last???.name:'wolverine'})
You with have to use the aggregation pipeline.
Use $project along with $arrayElemAt to extract the last element of the array
https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/
The you can use $match
i need to find documents where one field of the last element of array must comply one condition.
example in JS array[array.length-1].name == 'something'
collection.find({friends[lastelement].name:'something'})
Did you try using $aggregate, $project and $arrayElemAt?
I mean aggregate, not $aggregate
@AyushG3112 is right, the only way to do this is something like this:
People.aggregate([
{ $project: { lastFriend: { $arrayElemAt: ['$friends', -1] } } },
{ $match: { 'lastFriend.name': 'Wolverine' } }
]);
Although the above aggregation query will be slow if your 'people' collection is huge because it can't use any indexes. If you need to optimize this query you should store your array in reverse order or track a lastFriend
property.
@vkarpov15 Thank you, man! Much appreciated!
Most helpful comment
@AyushG3112 is right, the only way to do this is something like this:
Although the above aggregation query will be slow if your 'people' collection is huge because it can't use any indexes. If you need to optimize this query you should store your array in reverse order or track a
lastFriend
property.