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 (aggregation framework) to match a specific field value
To match a specific field value in MongoDB aggregation, use the $match operator. This operator filters documents based on specified criteria, similar to a find() query but within the aggregation pipeline.
Syntax
db.collection.aggregate([
{ $match: { fieldName: "value" } }
]);
Sample Data
db.demo555.insertMany([
{ "CountryName": "US" },
{ "CountryName": "UK" },
{ "CountryName": "US" },
{ "CountryName": "AUS" },
{ "CountryName": "US" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8f21bf54b4472ed3e8e85f"),
ObjectId("5e8f21c254b4472ed3e8e860"),
ObjectId("5e8f21c354b4472ed3e8e861"),
ObjectId("5e8f21c554b4472ed3e8e862"),
ObjectId("5e8f21c754b4472ed3e8e863")
]
}
Display all documents from the collection ?
db.demo555.find();
{ "_id": ObjectId("5e8f21bf54b4472ed3e8e85f"), "CountryName": "US" }
{ "_id": ObjectId("5e8f21c254b4472ed3e8e860"), "CountryName": "UK" }
{ "_id": ObjectId("5e8f21c354b4472ed3e8e861"), "CountryName": "US" }
{ "_id": ObjectId("5e8f21c554b4472ed3e8e862"), "CountryName": "AUS" }
{ "_id": ObjectId("5e8f21c754b4472ed3e8e863"), "CountryName": "US" }
Example: Match and Count Documents
Match documents where CountryName is "US" and count them ?
db.demo555.aggregate([
{ $match: { CountryName: "US" } },
{ $group: { _id: null, Total: { $sum: 1 } } }
]);
{ "_id": null, "Total": 3 }
Key Points
-
$matchshould be placed early in the aggregation pipeline for better performance. - It uses the same query syntax as
find()method. - Can be combined with other aggregation operators like
$group,$sort, and$project.
Conclusion
The $match operator is essential for filtering documents in MongoDB aggregation pipelines. It provides the same filtering capabilities as find() while allowing further processing with other aggregation stages.
Advertisements
