Mongoose sort the aggregated result

34,468

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.

Share:
34,468
Renan Basso
Author by

Renan Basso

Hello my friends, I'm a enthusiastic entrepreneur, always looking for new business strategies. Day by day I gave my best in decision-making, even outside my expertise area. Now I'm working hard on new products, finding new big opportunities and studing different businesses. Always focused on productivity to reach big results. Soft-skills: - Motivating - Creativity - Planning - Monitoring Hard-skills: - System Architect - Fullstack Engineering - Web Programming Languages (asp.net, node.js, j2ee, zendframework) - Database Manager (MS Server 2012, Oracle 10, MySQL, PostgresSQL) "You'll have to learn that the life give wings to who have no fear of falling" MB Labs Tecnologia!

Updated on June 02, 2020

Comments

  • Renan Basso
    Renan Basso almost 4 years

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