You can solve this using aggregation.
model.aggregate([
{
$addFields: {
lastArrayElement: {
$slice: ["$array", -1],
},
},
},
{
$match: {
"lastArrayElement.field": value,
},
},
]);
Quick explanations. aggregate
creates a pipeline of actions, executed sequentially, which is why it takes an array as parameter. First we use the $addFields
pipeline stage. This is new in version 3.4, and basically means: Keep all the existing fields of the document, but also add the following. In our case we're adding lastArrayElement
and defining it as the last element in the array called array
. Next we perform a $match
pipeline stage. The input to this is the output from the previous stage, which includes our new lastArrayElement
field. Here we're saying that we only include documents where its field field
has the value value
.
Note that the resulting matching documents will include lastArrayElement
. If for some reason you really don't want this, you could add a $project
pipeline stage after $match
to remove it.
$unwind
,$project
,$match
, and$group
– Quadruplefind({"array.-1.field":"value"})
– Sentimental