您可以将$avg运算符与聚合框架一起使用。首先让我们创建一个包含文档的集合-
> db.averageOfRatingsInArrayDemo.insertOne( ... { ... "StudentDetails":[ ... { ... "StudentId":1, ... "StudentScore":45 ... }, ... { ... "StudentId":2, ... "StudentScore":58 ... }, ... { ... "StudentId":3, ... "StudentScore":67 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd427dc2cba06f46efe9ee4") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.averageOfRatingsInArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd427dc2cba06f46efe9ee4"), "StudentDetails" : [ { "StudentId" : 1, "StudentScore" : 45 }, { "StudentId" : 2, "StudentScore" : 58 }, { "StudentId" : 3, "StudentScore" : 67 } ] }
以下是查询以计算数组中评分的平均值,然后在MongoDB中将字段包括到原始文档中-
> db.averageOfRatingsInArrayDemo.aggregate([ {$addFields : {StudentScoreAverage : {$avg : "$StudentDetails.StudentScore"}}} ]);
这将产生以下输出-
{ "_id" : ObjectId("5cd427dc2cba06f46efe9ee4"), "StudentDetails" : [ { "StudentId" : 1, "StudentScore" : 45 }, { "StudentId" : 2, "StudentScore" : 58 }, { "StudentId" : 3, "StudentScore" : 67 } ], "StudentScoreAverage" : 56.666666666666664 }