Find MongoDB documents where all objects in array have specific value?


Let us create a collection with documents −

> db.demo74.insertOne(
... {
... StudentName: "Chris",
... StudentDetails: [{
...    "Subject": "MongoDB",
...    "isRegular": "Active"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "InActive"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "InActive"
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c6b671bf0181ecc4226f")
}
> db.demo74.insertOne({
... name: "document2",
... data: [{
...    "Subject": "MongoDB",
...    "isRegular": "Active"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "Active"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "Active"
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c6b771bf0181ecc42270")
}

Display all documents from a collection with the help of find() method −

> db.demo74.find();

This will produce the following output −

{
   "_id" : ObjectId("5e29c6b671bf0181ecc4226f"), "StudentName" : "Chris", "StudentDetails" : [
      { "Subject" : "MongoDB", "isRegular" : "Active" },
      { "Subject" : "MongoDB", "isRegular" : "InActive" },
      { "Subject" : "MongoDB", "isRegular" : "InActive" }
   ]
}
{
   "_id" : ObjectId("5e29c6b771bf0181ecc42270"), "name" : "document2", "data" : [
      { "Subject" : "MongoDB", "isRegular" : "Active" },
      { "Subject" : "MongoDB", "isRegular" : "Active" },
      { "Subject" : "MongoDB", "isRegular" : "Active" }
   ] 
}

Following is the query to find documents where all objects in array have specific value −

> db.demo74.find({ " StudentDetails": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } }, "StudentDetails.isRegular": "Active" }).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e29c6b671bf0181ecc4226f"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "Subject" : "MongoDB",
         "isRegular" : "Active"
      },
      {
         "Subject" : "MongoDB",
         "isRegular" : "InActive"
      },
      {
         "Subject" : "MongoDB",
         "isRegular" : "InActive"
      }
   ]
}

Updated on: 30-Mar-2020

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements