- 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
Which MongoDB query finds same value multiple times in an array?
You can use $where operator along with some script.
Let us first create a collection with documents −
> dbsameValueMultipleTimesDemoinsertOne( { "ListOfPrice":[ {"Price": 110}, {"Price":130}, {"Price": 145} ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cefc4e6ef71edecf6a1f6b9") } > dbsameValueMultipleTimesDemoinsertOne( { "ListOfPrice":[ {"Price": 110}, {"Price":178}, {"Price": 110} ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cefc4e7ef71edecf6a1f6ba") }
Following is the query to display all documents from a collection with the help of find() method −
> dbsameValueMultipleTimesDemofind()pretty();
Output
{ "_id" : ObjectId("5cefc4e6ef71edecf6a1f6b9"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 130 }, { "Price" : 145 } ] } { "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }
Following is the query to find same value multiple times in an array −
> dbsameValueMultipleTimesDemofind({ "$where": function() { return thisListOfPricefilter(function(p) { return pPrice == 110; })length > 1; } })
Output
{ "_id" : ObjectId("5cefc4e7ef71edecf6a1f6ba"), "ListOfPrice" : [ { "Price" : 110 }, { "Price" : 178 }, { "Price" : 110 } ] }
Advertisements