이를 위해 $group 및aggregate()와 함께 $avg를 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo598.insertOne(
... {
... Information:'Student',
... id:100,
... details:[
... {Name:'Chris',Marks:75},
... {Name:'Bob',Marks:55}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e947fccf5f1e70e134e2694")
}
> db.demo598.insertOne(
... {
... Information:'Student',
... id:101,
... details:[
... {Name:'Chris',Marks:75},
... {Name:'Bob',Marks:45}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e947fcdf5f1e70e134e2695")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo598.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e947fccf5f1e70e134e2694"), "Information" : "Student", "id" : 100, "details" : [
{ "Name" : "Chris", "Marks" : 75 },
{ "Name" : "Bob", "Marks" : 55 }
] }
{ "_id" : ObjectId("5e947fcdf5f1e70e134e2695"), "Information" : "Student", "id" : 101, "details" : [
{ "Name" : "Chris", "Marks" : 75 },
{ "Name" : "Bob", "Marks" : 45 }
] } 다음은 문서 및 배열 요소에서 평균을 구하는 쿼리입니다. -
> db.demo598.aggregate([
...
... { "$group": {
... "_id": "Information",
... "id": { "$avg": "$id" },
... "details": { "$push": "$details" }
... }},
... { "$unwind": "$details" },
... { "$unwind": "$details" },
... { "$group": {
... "_id": { "Information": "$_id", "Name": "$details.Name" },
... "id": { "$avg": "$id" },
... "AvgValue": { "$avg": "$details.Marks" }
... }},
... { "$sort": { "_id": 1 } },
... { "$group": {
... "_id": "$_id.Information",
... "id": { "$avg": "$id" },
... "details": { "$push": {
... "Name": "$_id.Name",
... "MarksAvg": "$AvgValue"
... }}
... }}
... ]).pretty(); 이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : "Information",
"id" : 100.5,
"details" : [
{
"Name" : "Bob",
"MarksAvg" : 50
},
{
"Name" : "Chris",
"MarksAvg" : 75
}
]
}