$match (Filter Documents)

Last updated: 2026-10-09

$match (Filter Documents)

$match filters documents with a query condition, passing only matching documents to subsequent stages. It is the aggregation equivalent of find()'s query predicate. Place $match as early as possible — it can use indexes and reduces the document count entering later stages, making it the #1 aggregation performance rule.

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $match: { <query> } }

⚙️ Parameters

querySame query expression as find(), supporting comparison/logical/element operators.

Returns:Filtered document stream (for the next stage)

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $match: only orders with status A
db.orders.aggregate([
  { $match: { status: "A" } },
  { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
])

Output:

// Returns total per customer
{ "_id": "A123", "total": 250 }
{ "_id": "B456", "total": 130 }

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat is the difference between $match and find()?
AThe query conditions are identical, but $match is used inside an aggregation pipeline and passes results to the next stage.
QCan $match be placed in the middle of a pipeline?
AYes, but you lose index optimization. Rule of thumb: put it first whenever possible.
QWhy place $match at the start of the pipeline?
AFiltering early reduces the data volume passed to later stages and lets $match use an index, which significantly boosts performance. Placed later it still works but cannot use indexes.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏