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
Matching an array field that contains any combination of the provided array in MongoDB?
To match documents where an array field contains any combination of the provided array values in MongoDB, use the $not operator combined with $elemMatch and $nin. This approach finds documents where the array contains only elements from the specified set.
Syntax
db.collection.find({
arrayField: {
$not: {
$elemMatch: { $nin: ["value1", "value2", "value3"] }
}
}
});
Sample Data
db.combinationOfArrayDemo.insertMany([
{
"StudentName": "Larry",
"StudentAge": 21,
"StudentFavouriteTechnicalSubject": ["C", "Java"]
},
{
"StudentName": "Mike",
"StudentAge": 23,
"StudentFavouriteTechnicalSubject": ["C++", "Java"]
},
{
"StudentName": "David",
"StudentAge": 22,
"StudentFavouriteTechnicalSubject": ["Java"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c7f77cc8d10a061296a3c58"),
ObjectId("5c7f77dc8d10a061296a3c59"),
ObjectId("5c7f77f48d10a061296a3c5a")
]
}
Example: Find Arrays with Only C++ and Java
Find students whose favorite subjects contain only combinations of "C++" and "Java" ?
db.combinationOfArrayDemo.find({
StudentFavouriteTechnicalSubject: {
$not: {
$elemMatch: { $nin: ["C++", "Java"] }
}
}
}).pretty();
{
"_id": ObjectId("5c7f77dc8d10a061296a3c59"),
"StudentName": "Mike",
"StudentAge": 23,
"StudentFavouriteTechnicalSubject": ["C++", "Java"]
}
{
"_id": ObjectId("5c7f77f48d10a061296a3c5a"),
"StudentName": "David",
"StudentAge": 22,
"StudentFavouriteTechnicalSubject": ["Java"]
}
How It Works
-
$ninmatches elements NOT in the specified array ["C++", "Java"] -
$elemMatchchecks if any array element matches the $nin condition -
$notnegates the result, returning documents where NO elements are outside the allowed set
This query excludes Larry's document because "C" is not in the allowed ["C++", "Java"] set, but includes Mike and David since their arrays only contain elements from the specified combination.
Conclusion
Use $not with $elemMatch and $nin to find documents where array fields contain only specific combinations of values. This technique effectively filters arrays to match subsets of a provided array.
