将$avg运算符与聚合框架一起使用。首先让我们创建一个包含文档的集合。在这里,字段之一是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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.averageReturiningNullDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ce9822e78f00858fb12e927"), "StudentDetails" : { "StudentScore" : 89 } } { "_id" : ObjectId("5ce9822e78f00858fb12e928"), "StudentDetails" : { "StudentScore" : 34 } } { "_id" : ObjectId("5ce9822e78f00858fb12e929"), "StudentDetails" : { "StudentScore" : 78 } }
以下是对平均回报的查询-
> db.averageReturiningNullDemo.aggregate([ { "$group": { "_id": null, "StudentScoreAverage": { "$avg": "$StudentDetails.StudentScore" } } } ]);
这将产生以下输出-
{ "_id" : null, "StudentScoreAverage" : 67 }