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'}); } );
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.
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.
Definition. Sorts all input documents and returns them to the pipeline in sorted order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With