집계 프레임워크와 함께 $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 }