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

Updated on: 30-Jul-2019

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements