Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find MongoDB documents where all objects in array have specific value?
To find MongoDB documents where all objects in an array have a specific value, use the $not operator combined with $elemMatch to exclude documents that contain any non-matching values.
Syntax
db.collection.find({
"arrayField": {
"$not": {
"$elemMatch": { "field": { $ne: "desiredValue" } }
}
}
});
Sample Data
db.demo74.insertMany([
{
"StudentName": "Chris",
"StudentDetails": [
{ "Subject": "MongoDB", "isRegular": "Active" },
{ "Subject": "MongoDB", "isRegular": "InActive" },
{ "Subject": "MongoDB", "isRegular": "InActive" }
]
},
{
"name": "document2",
"data": [
{ "Subject": "MongoDB", "isRegular": "Active" },
{ "Subject": "MongoDB", "isRegular": "Active" },
{ "Subject": "MongoDB", "isRegular": "Active" }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e29c6b671bf0181ecc4226f"),
ObjectId("5e29c6b771bf0181ecc42270")
]
}
View All Documents
db.demo74.find();
{
"_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" }
]
}
Find Documents Where All Array Objects Have Specific Value
Find documents where all objects in the array have isRegular: "Active" ?
db.demo74.find({
"data": {
"$not": {
"$elemMatch": { "isRegular": { $ne: "Active" } }
}
}
}).pretty();
{
"_id": ObjectId("5e29c6b771bf0181ecc42270"),
"name": "document2",
"data": [
{
"Subject": "MongoDB",
"isRegular": "Active"
},
{
"Subject": "MongoDB",
"isRegular": "Active"
},
{
"Subject": "MongoDB",
"isRegular": "Active"
}
]
}
How It Works
-
$elemMatchmatches documents that contain at least one array element withisRegularnot equal to "Active" -
$notnegates this condition, returning documents where NO array element has a non-"Active" value - This effectively finds documents where ALL array elements have
isRegular: "Active"
Conclusion
Use $not with $elemMatch to find documents where all array objects match a specific value. This pattern excludes documents containing any non-matching array elements, ensuring all elements satisfy the condition.
Advertisements
