Mongodb 使用mongoosejs statics获得最高平均评级
我刚开始学猫鼬。我遇到了一个完整的例子 这里我有一个名为Movies的集合模式。示例文档如下所示Mongodb 使用mongoosejs statics获得最高平均评级,mongodb,mongoose,mongoose-schema,Mongodb,Mongoose,Mongoose Schema,我刚开始学猫鼬。我遇到了一个完整的例子 这里我有一个名为Movies的集合模式。示例文档如下所示 { "title": "Movie title", "year": "1920", "type": "movie", "images": ["url/of/image1", "url/of/image
{
"title": "Movie title",
"year": "1920",
"type": "movie",
"images": ["url/of/image1", "url/of/image2" ...],
"ratings" : [
{"comment" : "user1 comment", "rating" : 3.2},
{"comment" : "user2 comment", "rating" : 4},
{"comment" : "user3 comment", "rating" : 5},
{"comment" : "user4 comment", "rating" : 2},
....
]
}
我想获得评级最高的前10部电影。它应该只考虑具有至少10个等级<>强>的电影。如何使用mongoosejs statics执行此类操作聚合可以轻松完成这项工作 考虑为上面的查询建立一个索引(“ratings.9.rating”将避免计算数组的大小,并消耗更少的cpu和内存使用量,而不是使用$size)
db.collection.aggregate([
{
$match: {
"ratings.9.rating": {
$gte: 0
}
}
},
{
$unwind: "$ratings"
},
{
$group: {
_id: "$title",
avgRating: {
$avg: "$ratings.rating"
}
}
},
{
$sort: {
avgRating: -1
}
},
{ $limit: 10 }
])
db.collection.createIndex({"ratings.9.rating"});