Docs 主页 → 开发应用程序 → MongoDB Manual
$match(聚合)
定义
兼容性
可以使用 $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()
。
限制
使用 Atlas Search 筛选 Atlas 数据
对于存储在 MongoDB Atlas 中的数据,您可以在运行 查询时使用 Atlas Search 复合 运算符filter
$search
选项来匹配或筛选文档。在 }$match
$search
之后运行 的性能低于使用 复合$search
操作符filter
选项运行 。
要了解有关 filter
选项的更多信息,请参阅 Atlas 文档中的 compound。
举例
这些示例会使用包含以下文档且名为 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 }