MongoDB查询以计算平均值
要计算MongoDB中的平均值,请使用$avg。让我们创建一个包含文档的集合-
> db.demo80.insertOne({"Details":{"Price":10.5}}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bf43271bf0181ecc42297") } > db.demo80.insertOne({"Details":{"Price":50.3}}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bf43871bf0181ecc42298") } > db.demo80.insertOne({"Details":{"Price":100.10}}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bf43f71bf0181ecc42299") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo80.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2bf43271bf0181ecc42297"), "Details" : { "Price" : 10.5 } } { "_id" : ObjectId("5e2bf43871bf0181ecc42298"), "Details" : { "Price" : 50.3 } } { "_id" : ObjectId("5e2bf43f71bf0181ecc42299"), "Details" : { "Price" : 100.1 } }
以下是在MongoDB中获取平均值的查询-
> db.demo80.aggregate([ ... { ... "$group": { ... "_id": null, ... "AvgValue": { ... "$avg": "$Details.Price" ... } ... } ... } ... ]);
这将产生以下输出-
{ "_id" : null, "AvgValue" : 53.633333333333326 }