MongoDB SELECT COUNT GROUP BY?

MongoDBDatabaseBig Data Analytics

You can achieve this with the help of an aggregate framework. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

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

Display all documents from a collection with the help of find() method. The query is as follows −

> db.countGroupByDemo.find().pretty();

Output

{
   "_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"
}

Here is the query to select count group by −

> db.countGroupByDemo.aggregate([
... {"$group":{_id:"$StudentId",counter:{$sum:1}}}]);

Output

{ "_id" : 30, "counter" : 2 }
{ "_id" : 20, "counter" : 2 }
{ "_id" : 10, "counter" : 3 }
raja
Published on 28-Mar-2019 11:04:20
Advertisements