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

更新於: 2019 年 7 月 30 日

301 個瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始學習
廣告