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.
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).
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.
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].
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" } } ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With