On this page
$match (aggregation)
在本页面
Definition
$match
- 筛选文档以仅将符合指定条件的文档传递到下一个管道阶段。
$match阶段具有以下原型形式:
{ $match: { <query> } }
$match获取指定查询条件的文档。查询语法与读取操作查询语法相同;即$match不接受原始聚合表达式。而是使用$expr查询表达式在$match中包括聚合表达式。
Behavior
Pipeline Optimization
将$match尽早放置在集合pipeline中。由于$match限制了聚合管道中的文档总数,因此较早的$match操作将管道中的处理量减至最少。
如果将$match放在管道的最开始,则查询可以像其他db.collection.find()或db.collection.findOne()一样利用indexes的优势。
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
且小于90
或views
大于或等于1000
的文档。然后将这些文档通过管道传递到$group进行计数。聚合返回以下内容:
{ "_id" : null, "count" : 5 }
See also