Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

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

        }
    );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...