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

  • $match should 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.

Updated on: 2026-03-15T03:33:32+05:30

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements