
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Documents Where All Elements of an Array Have a Specific Value in MongoDB
You can use find() for this. Let us first create a collection with documents −
> db.findDocumentsDemo.insertOne( { _id: 101, "ProductDetails": [ { "ProductValue":100 }, { "ProductValue":120 } ] } ); { "acknowledged" : true, "insertedId" : 101 } > db.findDocumentsDemo.insertOne( { _id: 102, "ProductDetails": [ { "ProductValue":120}, { "ProductValue":120 }, { "ProductValue":120 } ] } ); { "acknowledged" : true, "insertedId" : 102 }
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentsDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "ProductDetails" : [ { "ProductValue" : 100 }, { "ProductValue" : 120 } ] } { "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }
Following is the query to find documents where all elements of an array have a specific value i.e. ProductValue 120 here −
> db.findDocumentsDemo.find({ "ProductDetails.ProductValue" : { }, "ProductDetails" : { $not : { $elemMatch : { "ProductValue" : { $ne : 120 } } } } });
This will produce the following output −
{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }
Advertisements