How to maintain the top count of array elements in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use aggregate framework. Let us first create a collection with documents −

> db.topCountArrayDemo.insertOne(
...    {"StudentId":101 , "StudentSubject": ["C", "MongoDB"]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6b3209cb58ca2b005e669")
}
> db.topCountArrayDemo.insertOne(
...    {"StudentId":102 , "StudentSubject": ["C", "Java"]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6b3219cb58ca2b005e66a")
}
> db.topCountArrayDemo.insertOne(
...    {"StudentId":103 , "StudentSubject": ["C", "MongoDB"]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6b3229cb58ca2b005e66b")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc6b3209cb58ca2b005e669"),
   "StudentId" : 101,
   "StudentSubject" : [
      "C",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5cc6b3219cb58ca2b005e66a"),
   "StudentId" : 102,
   "StudentSubject" : [
      "C",
      "Java"
   ]
}
{
   "_id" : ObjectId("5cc6b3229cb58ca2b005e66b"),
   "StudentId" : 103,
   "StudentSubject" : [
      "C",
      "MongoDB"
   ]
}

Following is the query to maintain the top count of array elements in MongoDB −

> db.topCountArrayDemo.aggregate(
...    [
...       {
...          $unwind: "$StudentSubject"
...       },
...       {
...          $group: {
...             _id: "$StudentSubject",
...             Frequency: {$sum: 1}
...          }
...       },
...       {
...          $sort: {Frequency:-1}
...       },
...       {
...          $limit: 2
...       }
...    ]
... ).pretty();

This will produce the following output −

{ "_id" : "C", "Frequency" : 3 }
{ "_id" : "MongoDB", "Frequency" : 2 }
raja
Published on 21-May-2019 08:34:58
Advertisements