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
Working with Aggregation to match all the values in MongoDB
To match all the values in MongoDB using aggregation, use $match with $and operator to combine multiple conditions. This allows you to filter documents that satisfy all specified criteria simultaneously.
Syntax
db.collection.aggregate([
{
$match: {
$and: [
{ "field1": "value1" },
{ "field2": "value2" },
{ "nested.field": "value" }
]
}
}
]);
Sample Data
db.demo574.insertOne({
"details1": {
"details2": {
"dueDate": new ISODate("2020-01-10"),
"Name": "Chris",
"UserInformation": {
"Name": "John",
"Marks": 78
},
"CountryName": "US"
},
"id": 101
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5e9167f3581e9acd78b427f6")
}
Display Documents
db.demo574.find();
{
"_id": ObjectId("5e9167f3581e9acd78b427f6"),
"details1": {
"details2": {
"dueDate": ISODate("2020-01-10T00:00:00Z"),
"Name": "Chris",
"UserInformation": {
"Name": "John",
"Marks": 78
},
"CountryName": "US"
},
"id": 101
}
}
Example: Match Multiple Conditions
Find documents that match all three conditions using $and operator ?
db.demo574.aggregate([
{
$match: {
$and: [
{ "details1.id": 101 },
{ "details1.details2.UserInformation.Name": "John" },
{ "details1.details2.Name": "Chris" }
]
}
}
]);
{
"_id": ObjectId("5e9167f3581e9acd78b427f6"),
"details1": {
"details2": {
"dueDate": ISODate("2020-01-10T00:00:00Z"),
"Name": "Chris",
"UserInformation": {
"Name": "John",
"Marks": 78
},
"CountryName": "US"
},
"id": 101
}
}
Key Points
-
$andrequires all conditions to be true for a document to match. - Use dot notation to access nested fields in complex document structures.
- The
$matchstage filters documents before passing them to subsequent pipeline stages.
Conclusion
The $match stage with $and operator effectively filters documents that satisfy multiple conditions simultaneously. This approach is essential for complex queries requiring all specified criteria to be met.
Advertisements
