如何在mongoDB中对每个组进行排序和限制.
考虑以下数据:
Country:USA,name:xyz,rating:10,id:x
Country:USA,name:xyz,rating:10,id:y
Country:USA,name:xyz,rating:10,id:z
Country:USA,name:abc,rating:5,id:x
Country:India,name:xyz,rating:5,id:x
Country:India,name:xyz,rating:5,id:y
Country:India,name:abc,rating:10,id:z
Country:India,name:abc,rating:10,id:x
Run Code Online (Sandbox Code Playgroud)
现在说我将按国家分组并按评级排序,并将每组的数据限制为2.
所以答案是:
Country:USA
name:xyz,rating:10,id:x
name:xyz,rating:10,id:y
Country:India
name:abc,rating:10,id:x
name:abc,rating:10,id:z
Run Code Online (Sandbox Code Playgroud)
我想只使用聚合框架来实现这一点.
我尝试将汇总排序用于评级,但只是查询在处理后没有结果.
我有以下架构的待售物品集合:
var itemSchema = new Schema({
"category" : { type : Schema.Types.ObjectId, ref : 'Category' },
"merchant" : { type : Schema.Types.ObjectId, ref : 'Merchant' },
"rating" : Number
})
Run Code Online (Sandbox Code Playgroud)
我继承了一个聚合查询,该查询返回与按类别划分的类别的项目,按商家分组,组按组中的最大评级排序:
Item.aggregate([
{ "$match" : { category : categoryId, merchant : { $ne : null }}},
{ "$group" : { _id : "$merchant",
rating : { $max : "$rating" },
items : { $push : "$$ROOT" }}},
{ "$sort" : { rating : -1 }}
], { allowDiskUse : true …Run Code Online (Sandbox Code Playgroud)