Mongoose sort the aggregated result

前端 未结 1 1930
时光取名叫无心
时光取名叫无心 2020-12-14 16:17

I\'m having a lot of difficulty in solving this mongodb (mongoose) problem.

There is this schema \'Recommend\' (username, roomId, ll and date) and its collection co

相关标签:
1条回答
  • 2020-12-14 16:50

    The results returned from the aggregation pipeline are just plain objects. So you do the sorting as a pipeline stage, not as a separate operation:

    Recommend.aggregate(
        [
            // Grouping pipeline
            { "$group": { 
                "_id": '$roomId', 
                "recommendCount": { "$sum": 1 }
            }},
            // Sorting pipeline
            { "$sort": { "recommendCount": -1 } },
            // Optionally limit results
            { "$limit": 5 }
        ],
        function(err,result) {
    
           // Result is an array of documents
        }
    );
    

    So there are various pipeline operators that can be used to $group or $sort or $limit and other things as well. These can be presented in any order, and as many times as required. Just understanding that one "pipeline" stage flows results into the next to act on.

    0 讨论(0)
提交回复
热议问题