如何在 MongoDB 中基于重复的 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 }