当前位置:网站首页>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版本新增) |
边栏推荐
- 解析steam教育中蕴含的众创空间
- Kubeadm初始化报错:[ERROR CRI]: container runtime is not running
- Numpy vstack and column_ stack
- Jerry's ad series MIDI function description [chapter]
- [C language] deep understanding of symbols
- Stealing others' vulnerability reports and selling them into sidelines, and the vulnerability reward platform gives rise to "insiders"
- torch. Tensor and torch The difference between tensor
- Methods of improving machine vision system
- EhLib 数据库记录的下拉选择
- Huawei ENSP simulator layer 3 switch
猜你喜欢

ArcGIS 10.2.2 | solution to the failure of ArcGIS license server to start

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

MP3是如何诞生的?

每日一题-LeetCode556-下一个更大元素III-字符串-双指针-next_permutation
![Compréhension approfondie du symbole [langue C]](/img/4b/26cf10baa29eeff08101dcbbb673a2.png)
Compréhension approfondie du symbole [langue C]

Word文档中标题前面的黑点如何去掉

Redis 排查大 key 的3种方法,优化必备

超详细教程,一文入门Istio架构原理及实战应用

Day24: file system

解析互联网时代的创客教育技术
随机推荐
更强的 JsonPath 兼容性及性能测试之2022版(Snack3,Fastjson2,jayway.jsonpath)
For MySQL= No data equal to null can be found. Solution
Jerry's ad series MIDI function description [chapter]
Open3D 曲面法向量计算
__ init__ () missing 2 required positive arguments
MP3是如何诞生的?
EhLib 数据库记录的下拉选择
输入的查询SQL语句,是如何执行的?
Daily question-leetcode556-next larger element iii-string-double pointer-next_ permutation
redis RDB AOF
【C语言】符号的深度理解
gtest从一无所知到熟练使用(4)如何用gtest写单元测试
numpy vstack 和 column_stack
ArcGIS 10.2.2 | solution to the failure of ArcGIS license server to start
为什么说不变模式可以提高性能
【公开课预告】:视频质量评价基础与实践
GTEST from ignorance to proficiency (4) how to write unit tests with GTEST
Can be displayed in CAD but not displayed in print
Exclusive interview of open source summer | new committer Xie Qijun of Apache iotdb community
Analysis of maker education technology in the Internet Era