For group query, use MongoDB $group and get the count with $sum. Let us create a collection with documents −
> db.demo676.insertOne({"Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41eed04263e90dac943f2") } > db.demo676.insertOne({"Marks":75}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef304263e90dac943f3") } > db.demo676.insertOne({"Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef404263e90dac943f4") } > db.demo676.insertOne({"Marks":65}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef704263e90dac943f5") } > db.demo676.insertOne({"Marks":65}); { "acknowledged" : true, "insertedId" : ObjectId("5ea41ef804263e90dac943f6") }
Display all documents from a collection with the help of find() method −
> db.demo676.find();
This will produce the following output −
{ "_id" : ObjectId("5ea41eed04263e90dac943f2"), "Marks" : 87 } { "_id" : ObjectId("5ea41ef304263e90dac943f3"), "Marks" : 75 } { "_id" : ObjectId("5ea41ef404263e90dac943f4"), "Marks" : 87 } { "_id" : ObjectId("5ea41ef704263e90dac943f5"), "Marks" : 65 } { "_id" : ObjectId("5ea41ef804263e90dac943f6"), "Marks" : 65 }
Following is the query to get the count of repeated marks −
> db.demo676.aggregate( { $group: { ... _id: {Marks: "$Marks" }, ... 'Count': { $sum :1 } ... }})
This will produce the following output −
{ "_id" : { "Marks" : 75 }, "Count" : 1 } { "_id" : { "Marks" : 65 }, "Count" : 2 } { "_id" : { "Marks" : 87 }, "Count" : 2 }