定义
兼容性
可以使用 $match 查找托管在以下环境中的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务 
- MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本 
- MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本 
语法
$match 阶段具有以下原型形式:
{ $match: { <query> } } 
$match 接受一个指定查询条件的文档。查询语法与读取操作查询语法相同,即 $match 不接受原始聚合表达式。请使用 $expr 查询表达式将聚合表达式包含在 $match 中。
行为
管道优化
- 尽可能早地将 - $match放在聚合管道中。由于- $match限制了聚合管道中的文档总数,因此早期的- $match操作会最大限度地减少管道中的处理量。
- 如果在管道的开头放置一个 - $match,查询可以像使用任何其他- db.collection.find()或- db.collection.findOne()那样使用索引。
查询谓词中的表达式
0、Null、False 或缺失值
如果满足以下条件之一,则 $match 阶段会从管道结果中过滤掉文档:
- $match查询谓词返回该文档的- 0、- null或- false值。
- $match查询谓词使用了该文档中缺少的字段。
限制
- $match查询语法与读取操作查询语法相同,即- $match不接受原始聚合表达式。要在- $match中包含聚合表达式,请使用- $expr查询表达式:- { $match: { $expr: { <aggregation expression> } } } 
- 不能将 - $match查询中的- $near或- $nearSphere用作该聚合管道的一部分。或者也可以:- 在 - $match阶段使用带- $center或- $centerSphere的- $geoWithin查询操作符。
 
- 要在 - $match阶段使用- $text,- $match阶段必须是管道的第一阶段。- 视图不支持 - $text。- 注意- $text提供自管理(非 Atlas)部署的文本查询功能。对于托管在 MongoDB Atlas 上的数据,MongoDB 提供了一种改进的全文查询解决方案 Atlas Search。
使用 Atlas Search 筛选 Atlas 数据
对于存储在 MongoDB Atlas 中的数据,在运行 $search 查询时,您可以使用 Atlas Search 复合操作符 filter 选项来匹配或过滤文档。在 $search 之后运行 $match 的性能低于使用复合操作符 filter 选项运行 $search 的性能。
要了解有关 filter 选项的更多信息,请参阅 Atlas 文档中的复合操作符。
示例
这些示例会使用包含以下文档且名为 articles 的集合:
{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 } { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 } { "_id" : ObjectId("55f5a192d4bede9ac365b257"), "author" : "ahn", "score" : 60, "views" : 1000 } { "_id" : ObjectId("55f5a192d4bede9ac365b258"), "author" : "li", "score" : 55, "views" : 5000 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b259"), "author" : "annT", "score" : 60, "views" : 50 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b25a"), "author" : "li", "score" : 94, "views" : 999 } { "_id" : ObjectId("55f5a1d3d4bede9ac365b25b"), "author" : "ty", "score" : 95, "views" : 1000 } 
相等匹配
以下操作使用 $match 来执行简易等值匹配:
db.articles.aggregate(     [ { $match : { author : "dave" } } ] ); 
$match 会选择 author 字段等于 dave 的文档,而聚合返回以下内容:
{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 } { "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 } 
执行计数
以下示例使用 $match 管道操作符选择要处理的文档,然后将结果导入到 $group 管道操作符,以计算文档的数量:
db.articles.aggregate( [   { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },   { $group: { _id: null, count: { $sum: 1 } } } ] ); 
在聚合管道中,$match 选择 score 大于 70 但小于 90 或 views 大于或等于 1000 的文档。然后,这些文档通过管道传送到 $group 进行计数。该聚合返回以下内容:
{ "_id" : null, "count" : 5 }