 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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 MongoDB documents where elements of an array have a specific value?
To match documents in MongoDB, use $elemMatch. Let us first create a collection with documents −
> db.demo15.insertOne({"Details":[{"Score":56},{"Score":78}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e0f7806d7df943a7cec4fab") } > db.demo15.insertOne({"Details":[{"Score":86},{"Score":86}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e0f7817d7df943a7cec4fac") } > db.demo15.insertOne({"Details":[{"Score":97},{"Score":85}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e0f7823d7df943a7cec4fad") } Following is the query to display all documents from a collection with the help of find() method −
> db.demo15.find();
This will produce the following output −
{ "_id" : ObjectId("5e0f7806d7df943a7cec4fab"), "Details" : [ { "Score" : 56 }, { "Score" : 78 } ] } { "_id" : ObjectId("5e0f7817d7df943a7cec4fac"), "Details" : [ { "Score" : 86 }, { "Score" : 86 } ] } { "_id" : ObjectId("5e0f7823d7df943a7cec4fad"), "Details" : [ { "Score" : 97 }, { "Score" : 85 } ] } Here is the query to find documents where all elements of an array have a specific value −
> db.demo15.find({ ...    "Details.Score" : { ...       $exists : true ...    }, ...    "Details" : { ...       $not : { ...          $elemMatch : { ...             "Score" : { ...                $ne : 86 ...             } ...          } ...       } ...    } ... }); This will produce the following output −
{ "_id" : ObjectId("5e0f7817d7df943a7cec4fac"), "Details" : [ { "Score" : 86 }, { "Score" : 86 } ] }Advertisements
 