Finding top N entries from the Array

2020-04-19 07:03发布

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.

1条回答
手持菜刀,她持情操
2楼-- · 2020-04-19 07:22

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.

db.eplat1.aggregate([
  { "$unwind": "$Trips" },
  { "$sort": { "_id": 1, "Tips.TripCount": -1 } },
  { "$group": {
    "_id": "$_id",
    "Trips": { "$push": "$Trips" },
    "maxTrip": { "$max": "$Trips.TripCount" }
  }},
  { "$sort": { "maxTrip": -1 } },
  { "$limit": 50 },
  { "$addFields": { "Trips": { "$slice": [ "$Trips", 0 , 2 ] } } }
])
查看更多
登录 后发表回答