 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Find MongoDB document with array containing the maximum occurrence of a specific value
For this, you can use aggregate(). Let us first create a collection with documents −
> db.countOccurrencesDemo.insertOne({"ListOfValues":[65,87,89,65,67,87,87,87]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e06ef9325ddae1f53b621eb") } > db.countOccurrencesDemo.insertOne({"ListOfValues":[102,65,87,65,89,65,89,65,89,65]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e06efaa25ddae1f53b621ec") } Following is the query to display all documents from a collection with the help of find() method −
> db.countOccurrencesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06ef9325ddae1f53b621eb"), "ListOfValues" : [ 65, 87, 89, 65, 67, 87, 87, 87 ] } { "_id" : ObjectId("5e06efaa25ddae1f53b621ec"), "ListOfValues" : [ 102, 65, 87, 65, 89, 65, 89, 65, 89, 65 ] } Here is the query to find document with array containing the maximum occurrence of a specific value −
> db.countOccurrencesDemo.aggregate( ...    [ ...       { "$project": { ...          "ListOfValues": 1, ...          "OccurencesValue": { ...             "$size": { ...                "$filter": { ...                   "input": "$ListOfValues", ...                   "as": "v", ...                   "cond": { "$eq": [ "$$v", 65] } ...                } ...             } ...          } ...       }}, ...       { "$group": { ...          "_id": "$OccurencesValue", ...          "MyValues": { "$push": "$$ROOT" } ...       }}, ...       { "$sort": { "_id": -1 } }, ...       { "$limit": 1 } ...    ] ... ); This will produce the following output −
{ "_id" : 5, "MyValues" : [ { "_id" : ObjectId("5e06efaa25ddae1f53b621ec"), "ListOfValues" : [ 102, 65, 87, 65, 89, 65, 89, 65, 89, 65 ], "OccurencesValue" : 5 } ] }Advertisements
 