当前位置:网站首页>MongoDB聚合操作总结
MongoDB聚合操作总结
2022-07-04 20:57:00 【cui_yonghua】
1. 聚合操作的作用
MongoDB 中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。
有点类似 SQL 语句中的 count(*)
, sum()
, avg()
。
2. aggregate() 方法
MongoDB中聚合的方法使用aggregate()。
语法格式:db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
案例:计算每个作者所写的文章数,使用aggregate()计算结果如下
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : 1}}}])
# 类似SQL语句
select by_user, count(*) from mycol group by by_user;
在上面的例子中,通过字段 by_user 字段对数据进行分组,并计算 by_user 字段相同值的总和。
3. 常见的聚合表达式
1、$sum 计算总和。
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : "$likes"}}}])
1、$avg 计算平均值
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$avg : "$likes"}}}])
1、$min 获取集合中所有文档对应值得最小值。
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$min : "$likes"}}}])
1、$max 获取集合中所有文档对应值得最大值。
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$max : "$likes"}}}])
1、$push 将值加入一个数组中,不会判断是否有重复的值。
db.mycol.aggregate([{
$group : {
_id : "$by_user", url : {
$push: "$url"}}}])
1、$addToSet 将值加入一个数组中,会判断是否有重复的值,若相同的值在数组中已经存在了,则不加入。
db.mycol.aggregate([{
$group : {
_id : "$by_user", url : {
$addToSet : "$url"}}}])
1、$first 根据资源文档的排序获取第一个文档数据。
db.mycol.aggregate([{
$group : {
_id : "$by_user", first_url : {
$first : "$url"}}}])
1、$last 根据资源文档的排序获取最后一个文档数据
db.mycol.aggregate([{
$group : {
_id : "$by_user", last_url : {
$last : "$url"}}}])
4. 管道的概念
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。
MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。
聚合管道示意图:
相当于Sql语句: Select cust_id,sum(amount)as total from orders where status= "A"
聚合框架中常用的几个操作:
$project
:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。$match
:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。$limit
:用来限制MongoDB聚合管道返回的文档数。$skip
:在聚合管道中跳过指定数量的文档,并返回余下的文档。$unwind
:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。$group
:将集合中的文档分组,可用于统计结果。$sort
:将输入文档排序后输出。$geoNear
:输出接近某一地理位置的有序文档。
案例1:$project
db.article.aggregate({
$project: {
title: 1, author: 1,}});
# 默认情况下_id字段是被包含的,如果要想不包含_id话可以这样
db.article.aggregate({
$project: {
_id : 0 ,title: 1 ,author: 1}});
案例2:$match
案例, 获取分数大于70小于或等于90记录,然后将符合条件的记录送到下一阶段$group管道操作符进行处理。
db.articles.aggregate([{
$match : {
score : {
$gt : 70, $lte : 90 } } },{
$group: {
_id: null, count: {
$sum: 1 } } }]);
案例3:经过$skip
管道操作符处理后,前五个文档被"过滤"掉。
db.article.aggregate({
$skip : 5 });
5. SQL和聚合对应关系
SQL术语、函数、概念 | MongoDB聚合操作 |
---|---|
WHERE | $match |
GROUP BY | $group |
HAVING | $match |
SELECT | $project |
ORDER BY | $sort |
LIMIT | $limit |
SUM() | $sum |
COUNT() | $sum |
join | $lookup (3.2版本新增) |
边栏推荐
- Super detailed tutorial, an introduction to istio Architecture Principle and practical application
- Huawei simulator ENSP common commands
- 每日一题-LeetCode1200-最小绝对差-数组-排序
- 输入的查询SQL语句,是如何执行的?
- 每日一题-LeetCode556-下一个更大元素III-字符串-双指针-next_permutation
- [C language] deep understanding of symbols
- Routing configuration and connectivity test of Huawei simulator ENSP
- CloudCompare&Open3D DBSCAN聚类(非插件式)
- Can be displayed in CAD but not displayed in print
- Jerry added the process of turning off the touch module before turning it off [chapter]
猜你喜欢
迈动互联中标北京人寿保险
Daily question-leetcode556-next larger element iii-string-double pointer-next_ permutation
TCP三次握手,四次挥手,你真的了解吗?
Maidong Internet won the bid of Beijing life insurance
WGCNA analysis basic tutorial summary
奋斗正当时,城链科技战略峰会广州站圆满召开
Keep on fighting! The city chain technology digital summit was grandly held in Chongqing
每日一题-LeetCode1200-最小绝对差-数组-排序
[early knowledge of activities] list of recent activities of livevideostack
Billions of citizens' information has been leaked! Is there any "rescue" for data security on the public cloud?
随机推荐
每日一题-LeetCode1200-最小绝对差-数组-排序
Flink1.13 SQL basic syntax (I) DDL, DML
【公开课预告】:视频质量评价基础与实践
Configuration of DNS server of Huawei ENSP simulator
Redis03 - network configuration and heartbeat mechanism of redis
Jerry's ad series MIDI function description [chapter]
gtest从一无所知到熟练使用(3)什么是test suite和test case
LambdaQueryWrapper用法
Use of class methods and class variables
The video sound of station B is very low - solution
Jerry's ad series MIDI function description [chapter]
Rotary transformer string judgment
How is the entered query SQL statement executed?
Interpreting the development of various intelligent organizations in maker Education
WGCNA analysis basic tutorial summary
Hash table
淘宝商品评价api接口(item_review-获得淘宝商品评论API接口),天猫商品评论API接口
旋变串判断
QT—双缓冲绘图
为什么说不变模式可以提高性能