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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...