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
MongoDB query for documents whose array elements does not have a specific value
To query documents whose array elements do not have a specific value in MongoDB, use the $elemMatch operator combined with $exists: false. This finds documents containing arrays where at least one element lacks the specified field.
Syntax
db.collection.find({
"arrayField": {
"$elemMatch": {
"fieldToCheck": { "$exists": false }
}
}
});
Sample Data
Let us create a collection with documents ?
db.demo239.insertMany([
{
"Name": "Chris",
"details": [
{ "DueDate": new ISODate("2019-01-21"), "ProductPrice": 1270 },
{ "DueDate": new ISODate("2020-02-12"), "ProductPrice": 2000 }
]
},
{
"Name": "David",
"details": [
{ "DueDate": new ISODate("2018-11-11"), "ProductPrice": 1450 },
{ "DueDate": new ISODate("2020-02-12") }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e441c6bf4cebbeaebec5157"),
ObjectId("5e441c6cf4cebbeaebec5158")
]
}
Display all documents from the collection ?
db.demo239.find();
{
"_id": ObjectId("5e441c6bf4cebbeaebec5157"),
"Name": "Chris",
"details": [
{ "DueDate": ISODate("2019-01-21T00:00:00Z"), "ProductPrice": 1270 },
{ "DueDate": ISODate("2020-02-12T00:00:00Z"), "ProductPrice": 2000 }
]
}
{
"_id": ObjectId("5e441c6cf4cebbeaebec5158"),
"Name": "David",
"details": [
{ "DueDate": ISODate("2018-11-11T00:00:00Z"), "ProductPrice": 1450 },
{ "DueDate": ISODate("2020-02-12T00:00:00Z") }
]
}
Example: Find Documents Missing ProductPrice
Query documents where at least one array element lacks the ProductPrice field ?
db.demo239.find({
"details": {
"$elemMatch": {
"DueDate": { "$exists": true },
"ProductPrice": { "$exists": false }
}
}
});
{
"_id": ObjectId("5e441c6cf4cebbeaebec5158"),
"Name": "David",
"details": [
{ "DueDate": ISODate("2018-11-11T00:00:00Z"), "ProductPrice": 1450 },
{ "DueDate": ISODate("2020-02-12T00:00:00Z") }
]
}
Key Points
-
$elemMatchmatches documents where at least one array element meets all specified conditions. -
$exists: falseidentifies array elements that lack a specific field. - The query returns David's document because one of his detail elements is missing ProductPrice.
Conclusion
Use $elemMatch with $exists: false to find documents containing arrays where at least one element lacks a specific field. This approach efficiently identifies incomplete data within array structures.
Advertisements
