当前位置:网站首页>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版本新增) |
边栏推荐
- Delphi soap WebService server-side multiple soapdatamodules implement the same interface method, interface inheritance
- 迈动互联中标北京人寿保险
- 【微信小程序】协同工作与发布
- 超详细教程,一文入门Istio架构原理及实战应用
- Analysis of maker education technology in the Internet Era
- Numpy vstack and column_ stack
- minidom 模塊寫入和解析 XML
- How was MP3 born?
- redis管道
- flink1.13 sql基础语法(一)DDL、DML
猜你喜欢
【公开课预告】:视频质量评价基础与实践
Compréhension approfondie du symbole [langue C]
How is the entered query SQL statement executed?
MP3是如何诞生的?
[leetcode] 17. Letter combination of telephone number
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
Shutter textfield example
Huawei ENSP simulator layer 3 switch
How was MP3 born?
redis03——Redis的网络配置与心跳机制
随机推荐
【C语言】符号的深度理解
How to implement Devops with automatic tools
Rotary transformer string judgment
【微信小程序】协同工作与发布
Exclusive interview of open source summer | new committer Xie Qijun of Apache iotdb community
torch. Tensor and torch The difference between tensor
gtest从一无所知到熟练使用(2)什么是测试夹具/装置(test fixture)
解读创客教育中的各类智能化组织发展
Go language loop statement (3 in Lesson 10)
Flutter在 release版本,打开后随机白屏不显示内容
Daily question -leetcode1200- minimum absolute difference - array - sort
GTEST from ignorance to proficiency (4) how to write unit tests with GTEST
How is the entered query SQL statement executed?
Golang interview finishing three resumes how to write
Redis bloom filter
Cadeus has never stopped innovating. Decentralized edge rendering technology makes the metauniverse no longer far away
GTEST from ignorance to skillful use (1) GTEST installation
Billions of citizens' information has been leaked! Is there any "rescue" for data security on the public cloud?
Minidom module writes and parses XML
杰理之AD 系列 MIDI 功能说明【篇】