版权声明:本文为博主原创文章,无需授权即可转载,甚至无需保留以上版权声明,转载时请务必注明作者。
https://blog.csdn.net/weixin_43453386/article/details/85065043
MongoDB——》聚合查询(project、match、group、limit、skip、unwind、sort)
db:当前数据库名
test:当前集合名
test集合中的数据如下图所示:
一、聚合
1、聚合
2、聚合运算符
序号 | 运算符 | 说明 |
---|---|---|
1 | $add | 计算数值的总和 |
2 | $divide | 给定两个数值,用第一个数除以第二个数 |
3 | $mod | 取模。 |
4 | $multiply | 计算数值数组的乘积 |
5 | $subtract | 给定两个数值,用第一个数减去第二个数 |
6 | $concat | 连接两个字符串 |
7 | $strcasecmp | 比较两个字符串并返回一个整数来反应比较结果 |
8 | $substr | 返回字符串的一部分 |
9 | $toLower | 将字符串转化为小写 |
10 | $toUpper | 将字符串转化为大写 |
二、聚合运算符
1、$project
- 修改输入文档的结构
- 重命名、增加或删除域
- 创建计算结果以及嵌套文档
1) 例:获取test集合的weight字段及name字段(_id显示)
db.test.aggregate(
{ $project : {
weight: 1 ,
name : 1
}}
);
2) 例:获取test集合的weight字段及name字段(_id不显示)
db.test.aggregate(
{ $project : {
_id : 0 ,
weight: 1 ,
name : 1
}}
);
3) 例:使用$add给weight字段的值加10,然后将结果赋值给一个新的字段:newWeight
db.test.aggregate(
{ $project : {
_id : 0 ,
name : 1 ,
weight : 1 ,
newWeight : { $add:["$weight", 10] }
}}
);
4) 例:把weight重命名为newWeight
db.test.aggregate(
{ $project : {
_id : 0 ,
name : 1 ,
weight : 1 ,
newWeight : "$weight"
}}
);
2、$match
- 用于过滤数据,只输出符合条件的文档
- 在$match中不能使用$geoNear地理空间操作符及$where表达式操作符
1) 例:获取test集合的weight>=0.5且weight<=1
db.test.aggregate( {
$match :
{ weight :
{ $gte : 0.5, $lte : 1 }
}
});
或者
db.test.aggregate([
{$match :
{ weight :
{ $gte : 0.5, $lte : 1 }
}
}
]);
2) 例:获取test集合的weight>=0.5且weight<=1,然后将符合条件的记录送到下一阶段$group管道操作符进行处理
db.test.aggregate([
{$match :
{ weight :
{ $gte : 0.5, $lte : 1 }
}
},
{ $group:
{ _id: null,
count: { $sum: 1 }
}
}
]);
3、$group
- 将集合中的文档分组,可用于统计结果
- 在$match中不能使用$geoNear地理空间操作符及$where表达式操作符
1) 例:获取test集合的weight>=0.5且weight<=1,然后将符合条件的记录送到下一阶段$group管道操作符进行处理
db.test.aggregate([
{$match :
{ weight :
{ $gte : 0.5, $lte : 1 }
}
},
{ $group:
{ _id: null,
count: { $sum: 1 }
}
}
]);
4、$limit
- $limit会接受一个数字n,返回结果集中的前n个文档
1) 例:查询5条文档记录
db.test.aggregate({ $limit : 5 });
5、$skip
- $skip接受一个数字n,丢弃结果集中的前n个文档
- 限定可以传递到聚合操作的下一个管道中的文档数量
1) 例:获取test集合中第5条数据之后的数据
db.test.aggregate({ $skip: 5 });