Finding top N entries from the Array

后端 未结 1 1335
渐次进展
渐次进展 2021-01-24 03:47

My collection is structured like this:

{
    \"_id\": 1,
    \"Trips\": [
        {
            \"EndID\": 5,
            \"Tripcount\": 12
        },
        {
         


        
相关标签:
1条回答
  • 2021-01-24 04:28

    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 ] } } }
    ])
    
    0 讨论(0)
提交回复
热议问题