计算数组中评分的平均值,然后将该字段包含到MongoDB中的原始文档中?
您可以将$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 }热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短