What kind of MongoDB query finds same value multiple times in an array?


To find same value multiple times, use $where in MongoDB. Let us create a collection with documents −

> db.demo188.insertOne(
...   {
...      "ListOfData":[
...         {"Data": 100},
...         {"Data": 200},
...         {"Data": 100}
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ad1c203d395bdc21346bd")
}
> db.demo188.insertOne(
...   {
...      "ListOfData":[
...         {"Data": 100},
...         {"Data": 200},
...         {"Data": 300}
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ad1c203d395bdc21346be")
}

Display all documents from a collection with the help of find() method −

> db.demo188.find();

This will produce the following output −

{ "_id" : ObjectId("5e3ad1c203d395bdc21346bd"), "ListOfData" : [ { "Data" : 100 }, { "Data" : 200 }, { "Data" : 100 } ] }
{ "_id" : ObjectId("5e3ad1c203d395bdc21346be"), "ListOfData" : [ { "Data" : 100 }, { "Data" : 200 }, { "Data" : 300 } ] }

Following is the query to find same value multiple times in an array −

> db.demo188.find({
...   "$where": function() {
...      return this.ListOfData.filter(function(d) {
...         return d.Data == 100;
...      }).length > 1;
...   }
...})

This will produce the following output −

{ "_id" : ObjectId("5e3ad1c203d395bdc21346bd"), "ListOfData" : [ { "Data" : 100 }, { "Data" : 200 }, { "Data" : 100 } ] }

Updated on: 27-Mar-2020

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements