Let us first create a collection with documents −
> db.demo232.insertOne({_id:101,Name:"Chris"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo232.insertOne({_id:102,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo232.insertOne({_id:103,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo232.insertOne({_id:104,Name:"David"});
{ "acknowledged" : true, "insertedId" : 104 }
> db.demo232.insertOne({_id:105,Name:"Chris"});
{ "acknowledged" : true, "insertedId" : 105 }Display all documents from a collection with the help of find() method −
> db.demo232.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" }
{ "_id" : 102, "Name" : "Bob" }
{ "_id" : 103, "Name" : "Bob" }
{ "_id" : 104, "Name" : "David" }
{ "_id" : 105, "Name" : "Chris" }Following is the query to get the frequency of name record in MongoDB −
> db.demo232.aggregate( { $group : {_id : "$Name", Frequency : { $sum : 1 }} } );This will produce the following output −
{ "_id" : "David", "Frequency" : 1 }
{ "_id" : "Bob", "Frequency" : 2 }
{ "_id" : "Chris", "Frequency" : 2 }