为此,请使用$ 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 } ] }