[英]Mongoose sort the aggregated result
I'm having a lot of difficulty in solving this mongodb (mongoose) problem. 我在解决这个mongodb(猫鼬)问题时遇到了很多困难。
There is this schema 'Recommend' (username, roomId, ll and date) and its collection contains recommendation of user. 这个架构'推荐'(用户名,roomId,ll和日期),其集合包含用户推荐。
I need to get a list of most recommended rooms (by roomId). 我需要获得最推荐的房间列表(按roomId)。 Below is the schema and my tried solution with mongoose query.
下面是架构和我尝试过的mongoose查询解决方案。
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. 因此,有各种管道运算符可用于
$group
或$sort
或$limit
等。 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.
只是理解一个“管道”阶段流动的结果导致下一个行动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.