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 documents where all elements of an array have a specific value in MongoDB?
To find documents where all elements of an array have a specific value in MongoDB, use the $not operator with $elemMatch to exclude documents that contain any element NOT matching the desired value.
Syntax
db.collection.find({
"arrayField": {
$not: {
$elemMatch: {
"field": { $ne: "specificValue" }
}
}
}
});
Sample Data
db.findDocumentsDemo.insertMany([
{
_id: 101,
"ProductDetails": [
{ "ProductValue": 100 },
{ "ProductValue": 120 }
]
},
{
_id: 102,
"ProductDetails": [
{ "ProductValue": 120 },
{ "ProductValue": 120 },
{ "ProductValue": 120 }
]
}
]);
{
"acknowledged": true,
"insertedIds": { "0": 101, "1": 102 }
}
Example: Find All ProductValue = 120
Find documents where all array elements have ProductValue of 120 ?
db.findDocumentsDemo.find({
"ProductDetails": {
$not: {
$elemMatch: {
"ProductValue": { $ne: 120 }
}
}
}
});
{
"_id": 102,
"ProductDetails": [
{ "ProductValue": 120 },
{ "ProductValue": 120 },
{ "ProductValue": 120 }
]
}
How It Works
-
$elemMatchfinds arrays containing at least one element NOT equal to 120 -
$notinverts this logic to exclude such documents - Result: only documents where all elements equal 120 remain
Conclusion
Use $not with $elemMatch and $ne to find documents where all array elements match a specific value. This approach excludes documents containing any non-matching elements.
Advertisements
