MongoDB 查询以对特定字段求和
要对特定字段求和,请使用聚合以及 $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" }
以下是根据 ACTIVE 状态对特定字段求和的查询 −
> db.getSumOfFieldsDemo.aggregate([ { $match: { Status: "Active" } }, { $group: { _id: "$Customer_Id", TotalSum: { $sum: "$Price" } } } ]);
这将产生以下输出 −
{ "_id" : 103, "TotalSum" : 400 } { "_id" : 101, "TotalSum" : 3050 }
广告