使用 MongoDB 聚合一组中的总数
若要聚合总数,请在 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 }
广告