计算数组中评分的平均值,然后将该字段添加到 MongoDB 中的原始文档中?
mongodbdatabasebig data analytics更新于 2026/1/12 14:22:17
您可以将 $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 }

