Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose sort the aggregated result

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 contains recommendation of user.

I need to get a list of most recommended rooms (by roomId). Below is the schema and my tried solution with mongoose query.

var recommendSchema = mongoose.Schema({     username: String,     roomId: String,     ll: { type: { type: String }, coordinates: [ ] },     date: Date }) recommendSchema.index({ ll: '2dsphere' });  var Recommend = mongoose.model('Recommend', recommendSchema); Recommend.aggregate(         {              $group:              {                  _id: '$roomId',                  recommendCount: { $sum: 1 }              }         },         function (err, res) {             if (err) return handleError(err);             var resultSet = res.sort({'recommendCount': 'desc'});          }     ); 
like image 679
Renan Basso Avatar asked Oct 29 '14 05:10

Renan Basso


People also ask

How do I sort data in MongoDB aggregation?

In MongoDB, the $sort stage is used to sort all the documents in the aggregation pipeline and pass a sorted order to the next stage of the pipeline. Lets take a closer look at the above syntax: The $sort stage accepts a document that defines the field or fields that will be used for sorting.

How do I sort an array in MongoDB aggregation?

To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.

What is sort aggregate?

Definition. Sorts all input documents and returns them to the pipeline in sorted order.


1 Answers

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.

like image 167
Neil Lunn Avatar answered Sep 20 '22 07:09

Neil Lunn