Find MongoDB documents where elements of an array have a specific value?

MongoDBDatabaseBig Data Analytics

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 } ] }
raja
Published on 01-Apr-2020 17:49:25
Advertisements