- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ] }
Advertisements