$match
用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
示例
现有集合 articles 文档内容如下:
db.articles.insert([{ "_id" : 1, "author" : "dave", "score" : 80, "views" : 100 },{ "_id" : 2, "author" : "dave", "score" : 85, "views" : 521 },{ "_id" : 3, "author" : "ahn", "score" : 60, "views" : 1000 },{ "_id" : 4, "author" : "li", "score" : 55, "views" : 5000 },{ "_id" : 5, "author" : "annT", "score" : 60, "views" : 50 },{ "_id" : 6, "author" : "li", "score" : 94, "views" : 999 },{ "_id" : 7, "author" : "ty", "score" : 95, "views" : 1000 }])
Match 匹配
利用 $match 执行匹配操作,如下:
db.articles.aggregate([ { $match : { author : "dave" } } ])
输出:
{ "_id" : 1, "author" : "dave", "score" : 80, "views" : 100 }
{ "_id" : 2, "author" : "dave", "score" : 85, "views" : 521 }
范围条件匹配
统计 articles 集合中 score在70~90中间,或者views大于等于1000
回想一下如果用 find() 如何查询?
db.articles.find( { $or: [ { score: { $gt: 70 }, score:{ $lt: 90 } }, { views: { $gte: 1000 } } ]})
执行输出:
{ "_id" : 1, "author" : "dave", "score" : 80, "views" : 100 }
{ "_id" : 2, "author" : "dave", "score" : 85, "views" : 521 }
{ "_id" : 3, "author" : "ahn", "score" : 60, "views" : 1000 }
{ "_id" : 4, "author" : "li", "score" : 55, "views" : 5000 }
{ "_id" : 5, "author" : "annT", "score" : 60, "views" : 50 }
{ "_id" : 7, "author" : "ty", "score" : 95, "views" : 1000 }
可以看到{ "_id" : 5, "author" : "annT", "score" : 60, "views" : 50 }
这个结果是不对的,为什么???
同一个score键,后者覆盖前者
db.articles.find( { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ]})
聚合match写法
db.articles.aggregate([ { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } }])
计算Count值
统计 articles 集合中 score在70~90中间,或者views大于等于1000 个数
db.articles.count( { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ]})
那如果使用聚合aggregate 如何来实现呢?
db.articles.aggregate([ { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } }, { $group: { _id: null, count: { $sum: 1 } } }] )
输出:
{ "_id" : null, "count" : 5 }
类似于SQL语句: select count(*) from articles where (score>70 and score<90) or views>=1000