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

Updated on: 01-Apr-2020

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements