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