MongoDB聚合管道:$match

$match是聚合管道中最常用的阶段之一,用于过滤管道中的文档,只允许符合条件的文档进入到管道的下一阶段。

语法

{$match:{<query>}}

使用举例

创建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 }

等式匹配


匹配作者为"dave"的文档
db.articles.aggregate(
    [ { $match : { author : "dave" } } ]
);

管道输出结果:

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

计数

匹配评分在70分到90分之间或者阅读量大于1000的记录,并统计数量

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

管道输出结果:

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

最佳实践

  • 应尽可能把$match放在管道的前面,这样可以最大程度的减少进入管道的文档数量,不仅可以减少内存的占用,也可以加快后续阶段的执行。
  • 如果$match放在管道的最前面,就能像find一样利用上索引了,执行效率会更高。

注意事项

  • $matchquery参数跟collection.find查询条件一样,只支持读取操作表达式,不支持原始聚合表达式,只能在$expr查询表达式中包含聚合表达式。比如:
    { $match: { $expr: { <aggregation expression> } } }
    
  • $match中,不能使用$where
  • $match中,不能使用$near$nearSphere,但是:
    • 可以使用$geoNeer替代match
    • $geoWithin可以与$center$centerSphere一起使用
  • 如果要在$match中使用$text,则必须要把$match放在聚合管道的第一个阶段。

内容参考MongoDB官方线上文档,错误纰漏之处请不吝指正。

你可能感兴趣的:(mongodb,mongodb,数据库)