$match (aggregation)

在本页面

Definition

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

{ $match: { <query> } }

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

Behavior

Pipeline Optimization

Restrictions

{ $match: { $expr: { <aggregation expression> } } }

Views不支持文本搜索。

Examples

这些示例使用名为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

以下操作使用$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 }
首页