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
Filter documents in MongoDB if all keys exist as fields?
To filter documents in MongoDB where all specified keys exist as fields in an array, use the $all operator. This operator matches documents containing all specified elements in the array, regardless of order.
Syntax
db.collection.find({
"arrayField": { "$all": ["value1", "value2", "value3"] }
});
Sample Data
db.demo17.insertMany([
{"ListOfSubject": ["MySQL", "MongoDB", "Java"]},
{"ListOfSubject": ["C", "Python", "Java"]},
{"ListOfSubject": ["C++", "MongoDB", "PL/SQL"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e13847255d0fc6657d21f0a"),
ObjectId("5e13847e55d0fc6657d21f0b"),
ObjectId("5e13849255d0fc6657d21f0c")
]
}
Verify Sample Data
db.demo17.find();
{ "_id": ObjectId("5e13847255d0fc6657d21f0a"), "ListOfSubject": ["MySQL", "MongoDB", "Java"] }
{ "_id": ObjectId("5e13847e55d0fc6657d21f0b"), "ListOfSubject": ["C", "Python", "Java"] }
{ "_id": ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject": ["C++", "MongoDB", "PL/SQL"] }
Example: Filter with $all Operator
Find documents that contain all three subjects: "C++", "PL/SQL", and "MongoDB" ?
db.demo17.find({
"ListOfSubject": { "$all": ["C++", "PL/SQL", "MongoDB"] }
});
{ "_id": ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject": ["C++", "MongoDB", "PL/SQL"] }
Key Points
- The
$alloperator requires all specified values to be present in the array. - Order of elements in the
$allarray doesn't matter. - The target array can contain additional elements beyond those specified in
$all.
Conclusion
Use $all to filter documents where an array field contains all specified values. This operator is perfect for "must have all" filtering scenarios in MongoDB arrays.
Advertisements
