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 with $all in array
In MongoDB, the $all operator is used to select documents where the value of a field is an array that contains all the specified elements. This operator matches documents where the array field contains every element listed in the $all array, regardless of order or additional elements.
Syntax
db.collection.find({
"arrayField": { $all: [element1, element2, ...] }
});
Create Sample Data
Let us create a collection with documents containing client details ?
db.demo163.insertMany([
{
"ClientDetails": [
{ "ClientName": "Chris" },
{ "ClientName": "David" }
]
},
{
"ClientDetails": [
{ "ClientName": "Mike" },
{ "ClientName": "Sam" }
]
},
{
"ClientDetails": [
{ "ClientName": "Robert" },
{ "ClientName": "Sam" }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3686d49e4f06af551997c5"),
ObjectId("5e3686d59e4f06af551997c6"),
ObjectId("5e3686d59e4f06af551997c7")
]
}
Display all documents from the collection ?
db.demo163.find();
{ "_id": ObjectId("5e3686d49e4f06af551997c5"), "ClientDetails": [ { "ClientName": "Chris" }, { "ClientName": "David" } ] }
{ "_id": ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails": [ { "ClientName": "Mike" }, { "ClientName": "Sam" } ] }
{ "_id": ObjectId("5e3686d59e4f06af551997c7"), "ClientDetails": [ { "ClientName": "Robert" }, { "ClientName": "Sam" } ] }
Example: Query with $all Operator
Find documents where ClientDetails array contains both Mike and Sam ?
db.demo163.find({
"ClientDetails": {
$all: [
{ "ClientName": "Mike" },
{ "ClientName": "Sam" }
]
}
});
{ "_id": ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails": [ { "ClientName": "Mike" }, { "ClientName": "Sam" } ] }
Key Points
- The
$alloperator requires that all specified elements exist in the array field. - Order of elements in the
$allarray doesn't matter. - The target array can contain additional elements beyond those specified in
$all.
Conclusion
The $all operator is essential for finding documents where an array field contains all specified elements. It ensures complete match validation when you need every listed element to be present in the target array.
Advertisements
