計算陣列中評分的平均值,然後再將該欄位包含到 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