Definition 定义
对文档(documents)进行筛选,只将符合指定条件(condition(s))的文档传递给下一个 pipeline stage。
$matchstage 的原型形式如下:
{ $match: { <query> } }
$match接收一个指定查询条件的文档。查询语法(query syntax)与读操作的查询语法相同;也就是说,$match不接受 raw aggregation expresssions(原始的聚合表达式)。相反,使用 $expr query expression(查询表达式)才可以在$match中包含 aggregation expression。
Behavior 行为
Pipeline Optimization 管道优化
- 在 aggregation pipeline 中尽可能早地放置
$match。因为$match限制了 aggregation pipeline 中的文档总数,较早的$match操作使 pipe(管道) 中的处理量最小。 如果你把
$match放在 pipeline 的最开始,则查询可以像 db.collection.find() 或 db.collection.findOne() 一样利用索引(index)。Restrictions 限制
$match查询语法与读操作查询语法相同;也就是说,$match不接受 raw aggregation expressions。要在$match中包含 aggregation expression,请使用 $expr query expression:
{ $match: { $expr: { <aggregation expression> } } }
- 你不能在
$match查询中使用 $where 作为 aggregation pipeline 的一部分。 - 你不能在
$match查询中使用 $near 或 $nearSphere 作为 aggregation pipeline 的一部分。作为替代,你可以:- 使用 $geoNear stage 而不是
$matchstage。 - 在
$matchstage 使用 $geoWithin 查询运算符与 $center 或 $centerSphere。
- 使用 $geoNear stage 而不是
- 要在
$matchstage 使用 $text,$matchstage 必须是 pipeline 的第一个 stage。Views(视图)不支持文本搜索(text search)。Example 例子
这些例子使用一个名为articles的 collection,其中有以下文档:{ "_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 相等匹配
下面的 operation 使用$match来进行简单的 equality match:db.articles.aggregate( [{ $match: { author: "dave" } }] )
$match选择了author字段等于dave的文档,aggregation 返回如下:{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 }{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 }
Perform a Count 执行统计
下面的例子使用$matchpipeline operator 选择要处理的文档,然后将结果输送给 $group pipeline operator 来计算文档的数量:
在 aggregation pipeline 中,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的文档。然后这些文档被输送(piped)到 $group 中进行计数(preform a count)。aggregation 的结果如下:{ "_id" : null, "count" : 5 }
TIP 参阅:
- Aggregation with the Zip Code Data Set 与邮编数据集进行聚合
- Aggregation with User Preference Data 与用户偏好数据进行聚合
参考
https://docs.mongodb.com/manual/reference/operator/aggregation/match
