您的位置:首页 > 数据库 > Mongodb

MongoDB小结28 - 聚合管道【$match】

2016-08-03 15:30 501 查看
过滤数据,过滤完的数据,接下来用作其他用。 (水龙头上的过滤器,过滤干净的水,接下来淘米,煮饭都可以,貌似扯远了。。。回!)

1.例子

db.articles.aggregate(
[
{ $match : { author : "dave" } }
]
);

过滤条件为键 author 值为 dave

结果为
{
"result" : [
{
"_id" : ObjectId("512bc95fe835e68f199c8686"),
"author": "dave",
"score" : 80
},
{ "_id" : ObjectId("512bc962e835e68f199c8687"),
"author" : "dave",
"score" : 85
}
],
"ok" : 1
}

2.再看一例
db.articles.aggregate(
[
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
]
);

这次有两步:

第一步,过滤 键 score 值 大于70 且 小于等于90 的文档,

再用group 对文档用 count 统计,统计方式 $sum 求和,步长为1。

因为group操作必须有个_id,所以给其置null。

结果为

{
"result" : [
{
"_id" : null,
"count" : 3
}
],
"ok" : 1
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: