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 } ] }

Updated on: 31-Mar-2020

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements