

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to maintain the top count of array elements in MongoDB?
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 }
- Related Questions & Answers
- Count number of elements in an array with MongoDB?
- How do I add a value to the top of an array in MongoDB?
- How to filter array elements in MongoDB?
- Get count of array elements from a specific field in MongoDB documents?
- How to count items in array with MongoDB?
- How to count unique elements in the array using java?
- MongoDB query to count the size of an array distinctly?
- MongoDB query to count the frequency of every element of the array
- Count the number of items in an array in MongoDB?
- MongoDB query to change order of array elements?
- Count the non-masked elements of the masked array in Numpy
- Return Top two elements from array JavaScript
- Count array elements that divide the sum of all other elements in C++
- Using count equivalent in MongoDB to find top users with max occurrence
- Count frequencies of all elements in array in Python
Advertisements