Database Manual / Reference / Query Language / Aggregation Stages

$match (aggregation stage)(聚合阶段)

Definition定义

$match
Filters documents based on a specified query predicate. Matched documents are passed to the next pipeline stage.根据指定的查询谓词筛选文档。匹配的文件被传递到下一个管道阶段。

Compatibility兼容性

You can use $match for deployments hosted in the following environments:您可以将$match用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

{ $match: { <query predicate> } }

The syntax for the $match query predicate is identical to the syntax used in the query argument of a find() command.$match查询谓词的语法与find()命令的query参数中使用的语法相同。

Behavior行为

Pipeline Optimization管道优化

  • Place the $match as early in the aggregation pipeline as possible. Because $match limits the total number of documents in the aggregation pipeline, earlier $match operations minimize the amount of processing down the pipe.$match尽可能早地放置在聚合管道中。因为$match限制了聚合管道中的文档总数,所以早期的$match操作可以最大限度地减少管道中的处理量。
  • If you place a $match at the very beginning of a pipeline, the query can take advantage of indexes like any other db.collection.find() or db.collection.findOne().如果将$match放在管道的最开始,则查询可以像任何其他db.collection.find()db.collection.findOne()一样利用索引

Expressions in Query Predicates查询谓词中的表达式

To include expressions in a query predicate, use the $expr operator.要在查询谓词中包含表达式,请使用$expr运算符。

0, Null, False or Missing Values0Null、False或缺失值

A $match stage filters out a document from pipeline results if one of the following conditions applies:如果满足以下条件之一,$match阶段将从管道结果中筛选出文档:

  • The $match query predicate returns a 0, null, or false value on that document.$match查询谓词在该文档上返回0nullfalse值。
  • The $match query predicate uses a field that is missing from that document.$match查询谓词使用了该文档中缺少的字段。

Restrictions限制

  • You cannot use $where in a $match stage.$match阶段,您不能使用$where
  • You cannot use $near or $nearSphere in a $match stage. As an alternative, you can either:您不能在$match阶段中使用$near$nearSphere。作为替代方案,您可以:

    • Use the $geoNear stage instead of the $match stage.使用$geoNear阶段而不是$match阶段。
    • Use the $geoWithin query predicate operator with $center or $centerSphere in the $match stage.$match阶段,将$geoWithin查询谓词运算符与$center$centerSphere一起使用。
  • To use $text in a $match stage, the $match stage has to be the first stage of the pipeline.要在$match阶段中使用$text$match步骤必须是管道的第一阶段。

    Views do not support $text.视图不支持$text

    Note

    $text provides text query capabilities for self-managed (non-Atlas) deployments. 为自我管理(非Atlas)部署提供文本查询功能。For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, MongoDB Search.对于托管在MongoDB上的数据,MongoDB还提供了改进的全文查询解决方案MongoDB搜索

Filter Data on Atlas by Using MongoDB Search使用MongoDB搜索在Atlas上筛选数据

For data stored in MongoDB Atlas, you can use the MongoDB Search compound Operator operator filter option to match or filter documents when running $search queries. 对于存储在MongoDB Atlas中的数据,您可以在运行$Search查询时使用MongoDB搜索复合运算符运算符filter选项来匹配或筛选文档。Running $match after $search is less performant than running $search with the compound Operator operator filter option.$search之后运行$match的性能不如使用复合运算符运算符filter选项运行$search

To learn more about the filter option, see compound Operator in the Atlas documentation.要了解有关filter选项的更多信息,请参阅Atlas文档中的复合运算符

Examples示例

MongoDB Shell

The examples use a collection named articles with the following documents:这些示例使用了一个名为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 }

Equality Match相等匹配

The following operation uses $match to perform an equality match:以下操作使用$match执行相等匹配:

db.articles.aggregate(
[ { $match : { author : "dave" } } ]
);

The $match selects the documents where the author field equals dave, and the aggregation returns the following:$match选择author字段等于dave的文档,聚合返回以下结果:

{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 }
{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 }

Perform a Count执行计数

The following example selects documents to process using the $match pipeline operator and then pipes the results to the $group pipeline operator to compute a count of the documents:以下示例使用$match管道运算符选择要处理的文档,然后将结果传输到$group管道运算符以计算文档计数:

db.articles.aggregate( [
{ $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );

In the aggregation pipeline, $match selects the documents where either the score is greater than 70 and less than 90 or the views is greater than or equal to 1000. 在聚合管道中,$match选择score大于70且小于90views大于或等于1000的文档。These documents are then piped to the $group to perform a count. The aggregation returns the following:然后,这些文档被管道传输到$组以执行计数。聚合返回以下内容:

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

Match Array Elements匹配数组元素

To filter documents from a collection or previous aggregation stage based on elements in an array, use the $elemMatch operator in the query predicate of the $match stage:要根据数组中的元素从集合或以前的聚合阶段筛选文档,请在$match阶段的查询谓词中使用$elemMatch运算符:

db.aggregate( [
{
$documents: [
{ student_id: 1, scores: [ 0.75, 0.65, 0.73 ] },
{ student_id: 2, scores: [ 0.9, 0.88, 0.98 ] },
{ student_id: 3, scores: [ 0.9, 0.84, 0.93 ] }
]
}, {
$match: {
scores: { $elemMatch: { $gte: 0.9 } }
}
}
] )
[
{ student_id: 2, scores: [ 0.9, 0.88, 0.98 ] },
{ student_id: 3, scores: [ 0.9, 0.84, 0.93 ] }
]
C#

The C# examples on this page use the sample_mflix database from the Atlas sample datasets. 本页上的C#示例使用Atlas示例数据集中的sample_mflix数据库。To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB .NET/C# Driver documentation.要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅MongoDB .NET/C#驱动程序文档中的入门

The following Movie class models the documents in the sample_mflix.movies collection:以下Movie类对sample_mflix.movies集合中的文档进行建模:

public class Movie
{
public ObjectId Id { get; set; }

public int Runtime { get; set; }

public string Title { get; set; }

public string Rated { get; set; }

public List<string> Genres { get; set; }

public string Plot { get; set; }

public ImdbData Imdb { get; set; }

public int Year { get; set; }

public int Index { get; set; }

public string[] Comments { get; set; }

[BsonElement("lastupdated")]
public DateTime LastUpdated { get; set; }
}

Note

ConventionPack for Pascal CasePascal大小写的约定包

The C# classes on this page use Pascal case for their property names, but the field names in the MongoDB collection use camel case. To account for this difference, you can use the following code to register a ConventionPack when your application starts:此页面上的C#类使用Pascal大小写作为其属性名,但MongoDB集合中的字段名使用驼峰大小写。为了解释这种差异,您可以在应用程序启动时使用以下代码注册ConventionPack

var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

To use the MongoDB .NET/C# driver to add a $match stage to an aggregation pipeline, call the Match() method on a PipelineDefinition object.要使用MongoDB NET/C#驱动程序向聚合管道添加$match阶段,请在PipelineDefinition对象上调用Match()方法。

The following example creates a pipeline stage that matches all Movie documents where the Title field is equal to "The Shawshank Redemption":以下示例创建了一个管道阶段,该阶段匹配所有Title字段等于"The Shawshank Redemption"(肖申克的救赎)的Movie文档:

var pipeline = new EmptyPipelineDefinition<Movie>()
.Match(m => m.Title == "The Shawshank Redemption");
Node.js

The Node.js examples on this page use the sample_mflix database from the Atlas sample datasets. 本页上的Node.js示例使用Atlas示例数据集中的sample_mflix数据库。To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB Node.js driver documentation.要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅MongoDB Node.js驱动程序文档中的入门

To use the MongoDB Node.js driver to add a $match stage to an aggregation pipeline, use the $match operator in a pipeline object.要使用MongoDB Node.js驱动程序向聚合管道添加$match阶段,请在管道对象中使用$match运算符。

The following example creates a pipeline stage that matches all movie documents where the title field is equal to "The Shawshank Redemption". The example then runs the aggregation pipeline:以下示例创建了一个管道阶段,该阶段匹配所有title字段等于"The Shawshank Redemption"(肖申克的救赎)的movie文档。然后,该示例运行聚合管道:

const pipeline = [
{
$match: {
title: "The Shawshank Redemption"
}
}
];

const cursor = collection.aggregate(pipeline);
return cursor;

Learn More了解更多

Refer to the Complete Aggregation Pipeline Tutorials for more information and use cases on aggregation.有关聚合的更多信息和用例,请参阅完整的聚合管道教程