要在MongoDB中汇总总和以获取总计数,可以使用$sum运算符。要了解上述概念,让我们使用文档创建一个集合-
> db.aggregateSumDemo.insertOne({"CustomerName":"Larry","Amount":140}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa0680f10143d8431e18") } > db.aggregateSumDemo.insertOne({"CustomerName":"Mike","Amount":160}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa1380f10143d8431e19") } > db.aggregateSumDemo.insertOne({"CustomerName":"Sam","Amount":300}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa1c80f10143d8431e1a") } > db.aggregateSumDemo.insertOne({"CustomerName":"David","Amount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa2580f10143d8431e1b") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.aggregateSumDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8baa0680f10143d8431e18"), "CustomerName" : "Larry", "Amount" : 140 } { "_id" : ObjectId("5c8baa1380f10143d8431e19"), "CustomerName" : "Mike", "Amount" : 160 } { "_id" : ObjectId("5c8baa1c80f10143d8431e1a"), "CustomerName" : "Sam", "Amount" : 300 } { "_id" : ObjectId("5c8baa2580f10143d8431e1b"), "CustomerName" : "David", "Amount" : 500 }
这是获取总数的查询。
情况1-查询如下-
> db.aggregateSumDemo.aggregate([ { ... $group: { ... _id: null, ... "TotalCount": { ... $sum:1 ... } ... } ... } ] );
以下是输出-
{ "_id" : null, "TotalCount" : 4 }
这是在MongoDB中汇总总和以获取总和的查询。
情况2-查询如下-
> db.aggregateSumDemo.aggregate([ { ... $group: { ... _id: null, ... "TotalAmount": { ... $sum: "$Amount" ... } ... } ... } ] );
以下是输出-
{ "_id" : null, "TotalAmount" : 1100 }