要汇总总数,请在MongoDB中使用$sum。让我们创建一个包含文档的集合-
> db.demo406.insertOne({"Score":35}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f99d5fac4d418a0178599") } > db.demo406.insertOne({"Score":55}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f99d8fac4d418a017859a") } > db.demo406.insertOne({"Score":35}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f99dcfac4d418a017859b") } > db.demo406.insertOne({"Score":45}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f99defac4d418a017859c") } > db.demo406.insertOne({"Score":65}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f99e3fac4d418a017859d") } > db.demo406.insertOne({"Score":45}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f99e6fac4d418a017859e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo406.find();
这将产生以下输出-
{ "_id" : ObjectId("5e6f99d5fac4d418a0178599"), "Score" : 35 } { "_id" : ObjectId("5e6f99d8fac4d418a017859a"), "Score" : 55 } { "_id" : ObjectId("5e6f99dcfac4d418a017859b"), "Score" : 35 } { "_id" : ObjectId("5e6f99defac4d418a017859c"), "Score" : 45 } { "_id" : ObjectId("5e6f99e3fac4d418a017859d"), "Score" : 65 } { "_id" : ObjectId("5e6f99e6fac4d418a017859e"), "Score" : 45 }
以下是汇总一组总计的查询-
> db.demo406.aggregate([ ... { "$group": { ... "_id": null, ... "Score1": { ... "$sum": { ... "$cond": [{ "$eq": [ "$Score", 35 ] }, 1, 0 ] ... } ... }, ... "Score2": { ... "$sum": { ... "$cond": [{ "$ne": [ "$Score", 35 ] }, 1, 0 ] ... } ... }, ... "Score3": { ... "$sum": { ... "$cond": [{ "$ne": [ "$Score", 59 ] }, "$Score", 0 ] ... } ... } ... }} ... ])
这将产生以下输出-
{ "_id" : null, "Score1" : 2, "Score2" : 4, "Score3" : 280 }