MongoDB查询以汇总特定字段
要对特定字段求和,请使用aggregate和$sum。首先让我们创建一个包含文档的集合-
> db.getSumOfFieldsDemo.insertOne({"Customer_Id":101,"Price":50,"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06cec29e4dae213890ac55") } > db.getSumOfFieldsDemo.insertOne({"Customer_Id":102,"Price":200,"Status":"Inactive"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06ced19e4dae213890ac56") } > db.getSumOfFieldsDemo.insertOne({"Customer_Id":101,"Price":3000,"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06cedd9e4dae213890ac57") } > db.getSumOfFieldsDemo.insertOne({"Customer_Id":103,"Price":400,"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06cee79e4dae213890ac58") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.getSumOfFieldsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e06cec29e4dae213890ac55"), "Customer_Id" : 101, "Price" : 50, "Status" : "Active" } { "_id" : ObjectId("5e06ced19e4dae213890ac56"), "Customer_Id" : 102, "Price" : 200, "Status" : "Inactive" } { "_id" : ObjectId("5e06cedd9e4dae213890ac57"), "Customer_Id" : 101, "Price" : 3000, "Status" : "Active" } { "_id" : ObjectId("5e06cee79e4dae213890ac58"), "Customer_Id" : 103, "Price" : 400, "Status" : "Active" }
以下是基于活动状态对特定字段求和的查询-
> db.getSumOfFieldsDemo.aggregate([ { $match: { Status: "Active" } }, { $group: { _id: "$Customer_Id", TotalSum: { $sum: "$Price" } } } ]);
这将产生以下输出-
{ "_id" : 103, "TotalSum" : 400 } { "_id" : 101, "TotalSum" : 3050 }