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 - How can I see if all elements of a field are contained in a superset?
To check if all elements of an array field are contained within a superset in MongoDB, use the $not operator combined with $elemMatch and $nin. This ensures no array element exists outside the specified superset.
Syntax
db.collection.find({
"arrayField": {
$not: {
$elemMatch: {
$nin: ["superset", "values", "here"]
}
}
}
});
Sample Data
db.demo624.insertMany([
{"ListOfName": ["John", "Chris", "David", "Bob"]},
{"ListOfName": ["John", "Chris"]},
{"ListOfName": ["John", "Chris", "Carol"]},
{"ListOfName": ["John", "Chris", "Bob"]},
{"ListOfName": ["John", "Chris", "Mike", "Robert"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e9ab3ff6c954c74be91e6a5"),
ObjectId("5e9ab4026c954c74be91e6a6"),
ObjectId("5e9ab4076c954c74be91e6a7"),
ObjectId("5e9ab40e6c954c74be91e6a8"),
ObjectId("5e9ab4186c954c74be91e6a9")
]
}
Example: Find Documents with Elements in Superset
Find documents where all names in ListOfName are contained in the superset ["John", "Chris", "David", "Bob"] ?
db.demo624.find({
"ListOfName": {
$not: {
$elemMatch: {
$nin: ["John", "Chris", "David", "Bob"]
}
}
}
});
{ "_id": ObjectId("5e9ab3ff6c954c74be91e6a5"), "ListOfName": ["John", "Chris", "David", "Bob"] }
{ "_id": ObjectId("5e9ab4026c954c74be91e6a6"), "ListOfName": ["John", "Chris"] }
{ "_id": ObjectId("5e9ab40e6c954c74be91e6a8"), "ListOfName": ["John", "Chris", "Bob"] }
How It Works
-
$ninfinds elements NOT in the superset -
$elemMatchmatches arrays containing at least one element NOT in the superset -
$notinverts the result, returning only arrays where ALL elements ARE in the superset
Conclusion
Use $not: {$elemMatch: {$nin: [superset]}} to find documents where all array elements exist within a specified superset. This pattern efficiently filters arrays to ensure complete subset containment.
Advertisements
