I have documents with the following structure:
{
...,
trials:[ {...,
ref:[{a:1,b:2},{a:2,b:2},...]
},
{...,
ref:[{a:1,b:2}]
},
...,
]
}
Where ref is an array guaranteed to be of length of at least 1.
If I want to count the individual occurrences of each of elements in each of the ref arrays I would use the following aggregation. (This works fine)
db.cl.aggregate([
{$unwind:"$trials"},
{$unwind:"$trials.ref"},
{$group:{_id:"$trials.ref", count:{$sum:1}}}
])
Now I want to do the same thing, but only with the last element in each ref array. I need a way to only select the last element of each array in the aggregation pipeline.
I first thought I could add a intermediate step to just get all the elements that I want to group by doing something like this:
db.cl.aggregate([
{$unwind:"$trials"},
{$group:{_id:null,arr:{$push:"$trials.ref.-1"}}},...
])
I've also tried using a position operator with $match.
db.cl.aggregate([
{$unwind:"$trials"},
{$match:{"trials.ref.$":-1}},...
])
Or trying to project the last element.
db.cl.aggregate([
{$unwind:"$trials"},
{$project:{ref:"$trials.ref.1"}}
])
Neither of these get me anywhere. The $pop operator is not valid in the aggregation pipeline. $last operator isn't really useful here.
Any ideas on how to only use the last element of the ref array? I'd rather keep with the aggregation framework and NOT use Map Reduce.
refarrays and do the computation locally, but I'd rather not.$slicein the aggregation framework. And this is a problem given what you want to do. You can emulate it with layers of$firstand$matchas shown. But there is no easy way to get the "n" results of an array per grouping. This is basically what you are asking.