简体   繁体   中英

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'});

        }
    );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM