Computer >> Máy Tính >  >> Lập trình >> MongoDB

Lấy điểm trung bình trong MongoDB với tổng hợp?

Sử dụng toán tử $ avg cùng với khung tổng hợp. Đầu tiên chúng ta hãy tạo một bộ sưu tập với các tài liệu. Ở đây, một trong các trường là StudentScore -

> db.averageReturiningNullDemo.insertOne(
   {"StudentDetails" : { "StudentScore" : 89 }
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9822e78f00858fb12e927")
}
> db.averageReturiningNullDemo.insertOne(
   {"StudentDetails" : { "StudentScore" : 34 }
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9822e78f00858fb12e928")
}
> db.averageReturiningNullDemo.insertOne(
   {"StudentDetails" : { "StudentScore" : 78 }
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9822e78f00858fb12e929")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.averageReturiningNullDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau -

{
   "_id" : ObjectId("5ce9822e78f00858fb12e927"),
   "StudentDetails" : {
      "StudentScore" : 89
   }
}
{
   "_id" : ObjectId("5ce9822e78f00858fb12e928"),
   "StudentDetails" : {
      "StudentScore" : 34
   }
}
{
   "_id" : ObjectId("5ce9822e78f00858fb12e929"),
   "StudentDetails" : {
      "StudentScore" : 78
   }
}

Sau đây là truy vấn để trả về trung bình -

> db.averageReturiningNullDemo.aggregate([
   {
      "$group": {
         "_id": null,
         "StudentScoreAverage": {
            "$avg": "$StudentDetails.StudentScore"
         }
      }
   }
]);

Điều này sẽ tạo ra kết quả sau -

{ "_id" : null, "StudentScoreAverage" : 67 }