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
How do you perform an AND query on an array in MongoDB?
To perform an AND query on an array in MongoDB, use the $all operator. This operator matches documents where the array field contains all the specified elements, regardless of order or additional elements.
Syntax
db.collection.find({
"arrayField": { $all: ["value1", "value2", "value3"] }
});
Sample Data
db.andQueryDemo.insertMany([
{
"StudentName": "Carol Taylor",
"FavouriteSubject": ["C", "Java", "MongoDB", "MySQL"]
},
{
"StudentName": "David Miller",
"FavouriteSubject": ["C++", "Java", "MongoDB", "SQL Server"]
},
{
"StudentName": "Carol Taylor",
"FavouriteSubject": ["Python", "PL/SQL"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc73e7a8f9e6ff3eb0ce433"),
ObjectId("5cc73ea48f9e6ff3eb0ce434"),
ObjectId("5cc73ed38f9e6ff3eb0ce435")
]
}
Example: Find Students with Both "Java" and "MongoDB"
Find all students who have both "Java" and "MongoDB" in their FavouriteSubject array ?
db.andQueryDemo.find({
"FavouriteSubject": { $all: ["Java", "MongoDB"] }
});
{
"_id": ObjectId("5cc73e7a8f9e6ff3eb0ce433"),
"StudentName": "Carol Taylor",
"FavouriteSubject": ["C", "Java", "MongoDB", "MySQL"]
}
{
"_id": ObjectId("5cc73ea48f9e6ff3eb0ce434"),
"StudentName": "David Miller",
"FavouriteSubject": ["C++", "Java", "MongoDB", "SQL Server"]
}
How It Works
The $all operator returns documents where the specified array field contains all the listed values. The order of elements doesn't matter, and the array can contain additional elements beyond those specified in the query.
Conclusion
Use $all for AND operations on arrays in MongoDB. It matches documents containing all specified elements, making it perfect for finding records that meet multiple array criteria simultaneously.
