计算数组中评分的平均值,然后再将该字段包含到 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 }
广告
数据结构
网络
关系型数据库
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP