MongoDB 彙總以獲取文件和陣列元素的平均值?
為此,請使用 $avg 以及 $group 和 aggregate()。讓我們建立一個帶有文件的集合 −
> 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
}
]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP