如何根据重复的 ID 在 MongoDB 中获得评级平均值?
要在 MongoDB 中计算平均值,请使用 $avg。我们创建一个带有文档的集合。此处,我们有重复的 ID 且每个都具有评分 −
> db.demo606.insertOne({id:1,rating:5});{ "acknowledged" : true, "insertedId" : ObjectId("5e972dfbf57d0dc0b182d623") } > db.demo606.insertOne({id:1,rating:4});{ "acknowledged" : true, "insertedId" : ObjectId("5e972dfef57d0dc0b182d624") } > db.demo606.insertOne({id:2,rating:3});{ "acknowledged" : true, "insertedId" : ObjectId("5e972e09f57d0dc0b182d625") } > db.demo606.insertOne({id:1,rating:null});{ "acknowledged" : true, "insertedId" : ObjectId("5e972e0ef57d0dc0b182d626") } > db.demo606.insertOne({id:2,rating:null});{ "acknowledged" : true, "insertedId" : ObjectId("5e972e15f57d0dc0b182d627") } > db.demo606.insertOne({id:2,rating:3});{ "acknowledged" : true, "insertedId" : ObjectId("5e972e1bf57d0dc0b182d628") }
借助 find() 方法从集合中显示所有文档 −
> db.demo606.find();
这会生成以下输出 −
{ "_id" : ObjectId("5e972dfbf57d0dc0b182d623"), "id" : 1, "rating" : 5 } { "_id" : ObjectId("5e972dfef57d0dc0b182d624"), "id" : 1, "rating" : 4 } { "_id" : ObjectId("5e972e09f57d0dc0b182d625"), "id" : 2, "rating" : 3 } { "_id" : ObjectId("5e972e0ef57d0dc0b182d626"), "id" : 1, "rating" : null } { "_id" : ObjectId("5e972e15f57d0dc0b182d627"), "id" : 2, "rating" : null } { "_id" : ObjectId("5e972e1bf57d0dc0b182d628"), "id" : 2, "rating" : 3 }
以下是根据重复 ID 获取评分平均值的查询 −
> db.demo606.aggregate( ... [ ... { "$group": { ... "_id": "$id", ... "AverageRating": { "$avg": { "$ifNull": ["$rating",0 ] } } ... }} ... ] ... );
这会生成以下输出 −
{ "_id" : 2, "AverageRating" : 2 } { "_id" : 1, "AverageRating" : 3 }
广告