Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$match(聚合)

在此页面上

  • 定义
  • 兼容性
  • 语法
  • 行为
  • 管道优化
  • 限制
  • 使用 Atlas Search 筛选 Atlas 数据
  • 举例
  • 相等匹配
  • 执行计数
$match

筛选文档,以便只将符合特定条件的文档传递到下一管道阶段。

可以使用 $match 查找托管在以下环境中的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

$match阶段具有以下原型形式:

{ $match: { <query> } }

$match接受指定查询条件的文档。查询语法与读取操作查询语法相同;即$match不接受原始聚合表达式。相反,请使用$expr查询表达式将聚合表达式包含在$match中。

对于存储在 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且小于90views大于或等于1000的文档。然后,这些文档通过管道输送到$group以执行计数。该聚合返回以下内容:

{ "_id" : null, "count" : 5 }

提示

另请参阅:

← $lookup(聚合)