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
Does aggregation query with $match works in MongoDB?
Yes, the $match operator works perfectly in MongoDB aggregation queries. It filters documents in the aggregation pipeline, similar to the find() method's query criteria, but as the first stage of data processing.
Syntax
db.collection.aggregate([
{ $match: { "field": "value" } },
// Additional pipeline stages...
]);
Sample Data
db.demo358.insertMany([
{ "ClientId": 101, "ClientName": "Chris", "ClientAge": 34 },
{ "ClientId": 102, "ClientName": "David", "ClientAge": 32 },
{ "ClientId": 103, "ClientName": "David", "ClientAge": 35 },
{ "ClientId": 104, "ClientName": "Bob", "ClientAge": 31 },
{ "ClientId": 105, "ClientName": "Chris", "ClientAge": 36 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e5692c0f8647eb59e5620cb"),
ObjectId("5e5692caf8647eb59e5620cc"),
ObjectId("5e5692d2f8647eb59e5620cd"),
ObjectId("5e5692ddf8647eb59e5620ce"),
ObjectId("5e5692e7f8647eb59e5620cf")
]
}
Display All Documents
db.demo358.find();
{ "_id": ObjectId("5e5692c0f8647eb59e5620cb"), "ClientId": 101, "ClientName": "Chris", "ClientAge": 34 }
{ "_id": ObjectId("5e5692caf8647eb59e5620cc"), "ClientId": 102, "ClientName": "David", "ClientAge": 32 }
{ "_id": ObjectId("5e5692d2f8647eb59e5620cd"), "ClientId": 103, "ClientName": "David", "ClientAge": 35 }
{ "_id": ObjectId("5e5692ddf8647eb59e5620ce"), "ClientId": 104, "ClientName": "Bob", "ClientAge": 31 }
{ "_id": ObjectId("5e5692e7f8647eb59e5620cf"), "ClientId": 105, "ClientName": "Chris", "ClientAge": 36 }
Example: Using $match with $count
Count all clients named "David" using $match and $count ?
db.demo358.aggregate([
{ $match: { "ClientName": "David" } },
{ $count: "ClientName" }
]);
{ "ClientName": 2 }
Key Points
-
$matchshould typically be the first stage in the pipeline to reduce data early - It uses the same query syntax as
find()method - Can be combined with other aggregation operators like
$count,$group, etc.
Conclusion
The $match operator is essential for filtering documents in MongoDB aggregation pipelines. It works efficiently when placed early in the pipeline and supports all MongoDB query operators.
Advertisements
