Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Query on the last element of an array?

I know that MongoDB supports the syntax find{array.0.field:"value"}, but I specifically want to do this for the last element in the array, which means I don't know the index. Is there some kind of operator for this, or am I out of luck?

EDIT: To clarify, I want find() to only return documents where a field in the last element of an array matches a specific value.

like image 437
Joseph Blair Avatar asked Feb 23 '15 18:02

Joseph Blair


People also ask

How do I get the last element in MongoDB?

To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).

How do you find the last one of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

What is the last element in an array?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].


1 Answers

In 3.2 this is possible. First project so that myField contains only the last element, and then match on myField.

db.collection.aggregate([    { $project: { id: 1, myField: { $slice: [ "$myField", -1 ] } } },    { $match: { myField: "myValue" } } ]); 
like image 73
jdeyrup Avatar answered Oct 28 '22 19:10

jdeyrup