MongoDB SELECT COUNT GROUP BY?
您可以在聚合框架的帮助下实现这一目标。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.countGroupByDemo.insertOne({"StudentId":10,"StudentName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7700871e9c5dd6f1f78296") } > db.countGroupByDemo.insertOne({"StudentId":10,"StudentName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77008f1e9c5dd6f1f78297") } > db.countGroupByDemo.insertOne({"StudentId":20,"StudentName":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7700971e9c5dd6f1f78298") } > db.countGroupByDemo.insertOne({"StudentId":30,"StudentName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7700a21e9c5dd6f1f78299") } > db.countGroupByDemo.insertOne({"StudentId":30,"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7700aa1e9c5dd6f1f7829a") } > db.countGroupByDemo.insertOne({"StudentId":10,"StudentName":"Maxwell"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7700b41e9c5dd6f1f7829b") } > db.countGroupByDemo.insertOne({"StudentId":20,"StudentName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5c7700bd1e9c5dd6f1f7829c") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.countGroupByDemo.find().pretty();
输出结果
{ "_id" : ObjectId("5c7700871e9c5dd6f1f78296"), "StudentId" : 10, "StudentName" : "John" } { "_id" : ObjectId("5c77008f1e9c5dd6f1f78297"), "StudentId" : 10, "StudentName" : "Carol" } { "_id" : ObjectId("5c7700971e9c5dd6f1f78298"), "StudentId" : 20, "StudentName" : "Sam" } { "_id" : ObjectId("5c7700a21e9c5dd6f1f78299"), "StudentId" : 30, "StudentName" : "Mike" } { "_id" : ObjectId("5c7700aa1e9c5dd6f1f7829a"), "StudentId" : 30, "StudentName" : "David" } { "_id" : ObjectId("5c7700b41e9c5dd6f1f7829b"), "StudentId" : 10, "StudentName" : "Maxwell" } { "_id" : ObjectId("5c7700bd1e9c5dd6f1f7829c"), "StudentId" : 20, "StudentName" : "Bob" }
这是按以下条件选择计数组的查询:
> db.countGroupByDemo.aggregate([ ... {"$group":{_id:"$StudentId",counter:{$sum:1}}}]);
输出结果
{ "_id" : 30, "counter" : 2 } { "_id" : 20, "counter" : 2 } { "_id" : 10, "counter" : 3 }