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
Fetch records in MongoDB on querying its subset
To fetch records in MongoDB that contain a subset of values within an array field, use the $all operator. This operator matches documents where the array field contains all the specified elements, regardless of their order or position.
Syntax
db.collection.find({
"arrayField": { $all: ["value1", "value2", "value3"] }
});
Sample Data
db.subsetOfAnArrayDemo.insertOne({
"StudentProgrammingSkills": [
"Java", "MongoDB", "MySQL", "C++", "Data Structure",
"Algorithm", "Python", "Oracle", "SQL Server"
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cb9d1e1895c4fd159f80804")
}
Display All Documents
db.subsetOfAnArrayDemo.find().pretty();
{
"_id": ObjectId("5cb9d1e1895c4fd159f80804"),
"StudentProgrammingSkills": [
"Java",
"MongoDB",
"MySQL",
"C++",
"Data Structure",
"Algorithm",
"Python",
"Oracle",
"SQL Server"
]
}
Query for Subset Match
Find documents where the student has both "MongoDB" and "MySQL" skills ?
db.subsetOfAnArrayDemo.find({
StudentProgrammingSkills: { $all: ["MongoDB", "MySQL"] }
}).pretty();
{
"_id": ObjectId("5cb9d1e1895c4fd159f80804"),
"StudentProgrammingSkills": [
"Java",
"MongoDB",
"MySQL",
"C++",
"Data Structure",
"Algorithm",
"Python",
"Oracle",
"SQL Server"
]
}
Key Points
- The
$alloperator requires all specified values to be present in the array - Order of elements in the
$allarray doesn't matter - Returns the complete document if the subset condition is satisfied
Conclusion
The $all operator is essential for querying documents based on array subsets in MongoDB. It ensures that all specified values exist within the target array field, making it perfect for skill-based or tag-based filtering scenarios.
Advertisements
