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

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: 2020-03-27T08:16:21+05:30

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements