当前位置:网站首页>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版本新增) |
边栏推荐
猜你喜欢

【LeetCode】17、电话号码的字母组合

改善机器视觉系统的方法

QT—双缓冲绘图

CloudCompare&Open3D DBSCAN聚类(非插件式)

解析steam教育中蕴含的众创空间

maya灯建模

Analysis of maker education technology in the Internet Era

Huawei ENSP simulator enables devices of multiple routers to access each other

Arcgis 10.2.2 | arcgis license server无法启动的解决办法

如何使用ConcurrentLinkedQueue做一个缓存队列
随机推荐
[weekly translation go] how to code in go series articles are online!!
maya灯建模
EhLib 数据库记录的下拉选择
【C语言】符号的深度理解
Cadeus has never stopped innovating. Decentralized edge rendering technology makes the metauniverse no longer far away
[C language] deep understanding of symbols
超详细教程,一文入门Istio架构原理及实战应用
ArcGIS 10.2.2 | solution to the failure of ArcGIS license server to start
哈希表(Hash Tabel)
Flutter TextField示例
Compréhension approfondie du symbole [langue C]
numpy vstack 和 column_stack
解读创客教育中的各类智能化组织发展
Lambdaquerywrapper usage
In the release version, the random white screen does not display the content after opening the shutter
股票开户佣金最低多少,炒股开户佣金最低网上开户安全吗
Three or two things about the actual combat of OMS system
Redis 排查大 key 的3种方法,优化必备
redis事务
Liu Jincheng won the 2022 China e-commerce industry innovation Figure Award