Mongoose: How query on the last element of array?

Created on 23 Oct 2017  路  6Comments  路  Source: Automattic/mongoose

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'})

Most helpful comment

@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.

All 6 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

lukasz-zak picture lukasz-zak  路  3Comments

adamreisnz picture adamreisnz  路  3Comments

adamreisnz picture adamreisnz  路  3Comments

CodeurSauvage picture CodeurSauvage  路  3Comments