在MongoDB中执行分组并汇总文档的价格记录
> db.demo527.insertOne({"Price":45.5});{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff2fef4dcbee04fbbbdc") } > db.demo527.insertOne({"Price":55.5});{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff34ef4dcbee04fbbbdd") } > db.demo527.insertOne({"Price":100.4});{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff39ef4dcbee04fbbbde") } > db.demo527.insertOne({"Price":200.6});{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff40ef4dcbee04fbbbdf") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo527.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8aff2fef4dcbee04fbbbdc"), "Price" : 45.5 } { "_id" : ObjectId("5e8aff34ef4dcbee04fbbbdd"), "Price" : 55.5 } { "_id" : ObjectId("5e8aff39ef4dcbee04fbbbde"), "Price" : 100.4 } { "_id" : ObjectId("5e8aff40ef4dcbee04fbbbdf"), "Price" : 200.6 }
以下是对价格记录求和的查询-
> db.demo527.aggregate([ { $group: { _id:null, totalPrice:{"$sum":"$Price"}} } ])
这将产生以下输出-
{ "_id" : null, "totalPrice" : 402 }