My collection is structured like this:
{
"_id": 1,
"Trips": [
{
"EndID": 5,
"Tripcount": 12
},
{
"EndID": 6,
"Tripcount": 19
}
],
"_id": 2,
"Trips": [
{
"EndID": 4,
"Tripcount": 12
},
{
"EndID": 5,
"Tripcount": 19
}
], ...
}
As it can be seen, every document has a Trips
array. Now what I want to find, is the top N Tripcounts of all the Trips
arrays combined across the documents in the collection. Is that possible?
I already have the following, however this only takes the single greatest Tripcount
from each Trips
array and then outputs 50 of them. So actually having the top 2 trips in one Trips
array results in this query dropping the second one:
var group = db.eplat1.aggregate([
{ "$unwind": "$Trips"},
{ "$sort": {
"Trips.Tripcount": -1
}
},
{ "$limit": 50 },
{ "$group": {
"_id": 1,
"Trips": {
"$push": {
"Start": "$_id",
"Trips": "$Trips"
}
}
}}
], {allowDiskUse: true})
Note that I believe this problem is different to this one, as there only one document is given.
Basically you need to sort the array elements (
$unwind
/$sort
/$group
) and then you can do your$sort
for the top values and$limit
the results.Finally you
$slice
for the "top N" in the documents in the array.