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.
Version 3.6 use aggregation to achieve the same.
use $slice.
Editing: You can make use of
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
to find a match.But it won't give exactly what you are looking for. I don't think that is possible in mongoDB yet.
I posted on the official Mongo Google group here, and got an answer from their staff. It appears that what I'm looking for isn't possible. I'm going to just use a different schema approach.
You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.
Compare
query operators
vsaggregation comparison operators
.For scalar arrays
For embedded arrays - Use
$arrayElemAt
expression with dot notation to project last element.Spring
@Query
codeIn 3.2 this is possible. First project so that myField contains only the last element, and then match on myField.
Not sure about performance, but this works well for me: