MongoDB SELECT 按组计数?


借助聚合框架,您可以实现此目标。为了理解这个概念,让我们创建一个带文档的集合。用于使用文档创建集合的查询如下:

> 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() 方法显示集合中的所有文档。查询如下:

> 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 }

更新时间:30-Jul-2019

浏览 243 次

开启您的 职业生涯

完成课程取得认证

开始学习
广告