数据库mongodb基础操作

mongodb Aggregation聚合操作之$match

2021-03-09  本文已影响0人  蚁族的乐土

在上一篇 mongodb Aggregation聚合操作之$count 中详细介绍了mongodb聚合操作中的$count使用以及参数细节。本篇将开始介绍Aggregation聚合操作中的$match操作。

说明:

筛选文档,只将匹配指定条件的文档传递到下一个管道阶段。

语法:

{ $match: { <query> } }

1. 示例

初始化数据:

db.articles.insertMany([{ "_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 }])

示例:

db.articles.aggregate( [

  { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },

  { $group: { _id: null, count: { $sum: 1 } } }

] );

返回结果:

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

上一篇下一篇

猜你喜欢

热点阅读