FastAPI+React全栈开发10 MongoDB聚合查询
Chapter02 Setting Up the Document Store with MongoDB
10 Aggregation framework
FastAPI+React全栈开发10 MongoDB聚合查询
In the following pages, we will try to provide a brief introducton to the MongoDB aggregation framework, what it is, what benefits it offers, and why it is regarded as one of the strongest selling points of the MongoDB ecosystem.
在接下来的几页中,我们将简要介绍MongoDB聚合框架,它是什么,它提供了什么好处,以及为什么它被认为是MongoDB生态系统最强大的卖点之一。
Gentered around the concept of a pipeline (something that you might be familiar with if you have done some analytics or if you have ever connected a few commands in Linux), the aggregation framework is, at its simplest, an alternative way to retrieve sets of documents from a collection, it is similar to the find method that we already used extensively but with the additional benefit of the possibility of data processing in different stages or steps.
聚合框架是围绕管道的概念产生的(如果您做过一些分析,或者您曾经在Linux中连接过几个命令,您可能会熟悉这个概念),它是最简单的一种从集合中检索文档集的替代方法,它类似于我们已经广泛使用的find方法,但具有在不同阶段或步骤中进行数据处理的可能性的额外好处。
With the aggregation pipeline, we basically pull documents from a MongoDB collection and feed them sequentially to various stages of the pipeline where each stage output is fed to the next stage’s input until the final set of documents is returned. Each stage performs some data-processing operations on the currently selected documents, which include modifying documents, so the output documents often have a completely different structure.
使用聚合管道,我们基本上从MongoDB集合中提取文档,并依次将它们提供给管道的各个阶段,其中每个阶段的输出被馈送到下一阶段的输入,直到返回最终的文档集。每个阶段对当前选择的文档执行一些数据处理操作,其中包括修改文档,因此输出文档通常具有完全不同的结构。
1、$match: Match only specific documents, i.e. a particular brand.
2、$project: Selcect existing fields or derive new ones, brand and model.
3、$group: Group according to a categorical feature, like brand.
4、$sort: Sort in ascending or descending order using a field.
5、$limit: Limit the results to a predefined number.
1、$match:只匹配特定的文档,即特定的品牌。
2、$project:选择现有领域或衍生新的领域、品牌和模型。
3、$group:根据分类特征进行分组,如品牌。
4、$sort:使用字段按升序或降序排序。
5、$limit:将结果限制在预定义的数量内。
The operations that can be included in the stages are, for example, match, which is used to include only a subset of the entire collection, sorting, grouping, and projections. The MongoDB documentation site is the best place to start if you want to get acquainted with all the possibilities, but we want to start with a couple of simple examples.
这些阶段中可以包含的操作有,例如匹配,它用于只包含整个集合、排序、分组和投影的一个子集。如果您想了解所有的可能性,MongoDB文档站点是最好的起点,但是我们想从几个简单的示例开始。
The syntax for the aggregation is similar to other methods, we use the aggregate method, which takes a list of stages as a parameter.
聚合的语法与其他方法类似,我们使用aggregate方法,它将阶段列表作为参数。
Probably the best aggregation, to begin with, would be to mimic the find method. Let’s try to get all the Fiat cars in our collection as follows.
首先,最好的聚合可能是模仿find方法。让我们按照下面的方式尝试获取我们收集的所有菲亚特汽车。
db.cars.aggregate([{$match:{brand:"Fiat"}}])
import mongo6client = mongo6.MongoClient('mongodb://zhangdapeng:zhangdapeng520@192.168.234.130:27017/')
db = client["carsDB"]
cars = db["cars"]query = [{"$match": {"brand": "Fiat"}}]
r = cars.aggregate(query)
print(list(r))
This is probably the simplest possible aggregation and it consists of just one stage, the $match stage, which tells MongoDB that we only want the Fiats, so the out put of the first stage is exactly that.
这可能是最简单的聚合,它只包含一个阶段,即$match阶段,它告诉MongoDB我们只需要Fiats,因此第一阶段的输出正是如此。
Let’s say that in the second stage we want to group our Fiat cars by model and then check the average price for every model. The second stage is a bit more complicated, but bear with us, it is not that hard. Run the following lines of code.
假设在第二阶段,我们希望按车型对菲亚特汽车进行分组,然后检查每个车型的平均价格。第二阶段有点复杂,但请耐心等待,这并不难。运行以下代码行。
import mongo6client = mongo6.MongoClient('mongodb://zhangdapeng:zhangdapeng520@192.168.234.130:27017/')
db = client["carsDB"]
cars = db["cars"]query = [{"$match": {"brand": "Fiat"}}, # 找到菲亚特的汽车{"$group": {"_id": "$make", "avg_price": {"$avg": "$price"}}}, # 按照make字段分组,求price的平均值
]
r = cars.aggregate(query)
print(list(r))
The second stage uses the KaTeX parse error: Expected '}', got 'EOF' at end of input: …e part {model:"make"} is a bit counterintuitive, but it just gives MongoDB the following two important pieces of information:
- model: Without quotes or the dollar sign, it is the key that will be used for the grouping, and in our case, it makes sense that it is called model. We can call it any way we want; it is the key that will indicate the field that we are doing the grouping by.
- $make: It is actually required to be one of the fields present in the documents. In our case, it is called make and the dollar sign means that it is a field in the document. Other possibilities would be the year, the gearbox, and really any document field that has a categorical or ordinal meaning. The price wouldn’t make much sense.
第二阶段使用KaTeX parse error: Expected '}', got 'EOF' at end of input: …的文档键。部分{model:"make"}有点违反直觉,但它只是给MongoDB以下两个重要的信息:
- model:没有引号或美元符号,它是将用于分组的键,在我们的例子中,它被称为model是有意义的。我们可以随意称呼它;这是一个键,它将指示我们进行分组的字段。
- $make:它实际上需要是文档中存在的字段之一。在我们的示例中,它被称为make,美元符号表示它是文档中的一个字段。其他可能是年份、变速箱,以及任何具有分类或顺序含义的文档字段。这个价格不太合理。
The second argument in the group stage is the actual aggregation, as follows:
- avgPrice: This is the chosen name for the quantity that we wish to map. In our case, it makes sense to call it avgPrice, but we can choose this variable’s name as we please.
- $avg: This is one of the available aggregation functions such as average, count, sum, maximum, minimum, and so on. In this example, we could have used the minimum function instead of the average function in order to get the cheapest Fiat for every model.
- $price: like $make in the preceding part of the expression, this is a field belonging to the documents and it should be numeric, since calculating the average or the minimum of a sting doesn’t make much sense.
小组阶段的第二个参数是实际的聚合,如下所示:
- avgPrice:这是我们希望映射的数量的选择名称。在我们的示例中,将其称为avgPrice是有意义的,但是我们可以根据需要选择这个变量的名称。
- $avg:这是一个可用的聚合函数,如average, count, sum, maximum, minimum等。在这个例子中,我们可以使用最小函数而不是平均函数,以便为每个型号获得最便宜的菲亚特。
- p r i c e : 就像表达式前面的 price:就像表达式前面的 price:就像表达式前面的make一样,这是一个属于文档的字段,它应该是数字的,因为计算平均值或最小值没有多大意义。
Pipelines can also include data processing through the project operator, a handy tool for creating entirely new fields, derived from existing document fields, that are then carried into the next stages.
管道还可以包括通过项目操作员进行的数据处理,这是一种方便的工具,用于创建从现有文档字段派生的全新字段,然后将其带入下一阶段。
We will provide just another example to showcase the power of project in a pipeline stage. Let’s consider the following aggregation.
我们将提供另一个例子来展示项目在管道阶段的力量。让我们考虑下面的聚合。
import mongo6client = mongo6.MongoClient('mongodb://zhangdapeng:zhangdapeng520@192.168.234.130:27017/')
db = client["carsDB"]
cars = db["cars"]query = [{"$match": {"brand": "Opel"}}, # 查找{"$project": {"_id": 0, "price": 1, "year": 1, "fullName": {"$concat": ["$make", " ", "$brand"]}}}, # 过滤{"$group": {"_id": {"make": "$fullName"}, "avgPrice": {"$avg": "$price"}}}, # 分组{"$sort": {"avgPrice": -1}}, # 排序,根据平均价格降序{"$limit": 10}, # 限制返回数量
]
r = cars.aggregate(query)
print(list(r))
This might look intimidating at first, but it is mostly composed of elements that we have already seen. There is the $match stage (we select only the Opel cars), and there is sorting by the price in descending order and cutting off at the 10 priciest cars at the end. But the projection in the middle? It is just a way to craft new variables in a stage using existing ones.
乍一看可能有点吓人,但它主要是由我们已经见过的元素组成的。有$match阶段(我们只选择欧宝汽车),还有按价格降序排序,并在最后切断10辆最昂贵的汽车。但是中间的投影呢?这只是一种使用现有变量在阶段中创建新变量的方法。
相关文章:
FastAPI+React全栈开发10 MongoDB聚合查询
Chapter02 Setting Up the Document Store with MongoDB 10 Aggregation framework FastAPIReact全栈开发10 MongoDB聚合查询 In the following pages, we will try to provide a brief introducton to the MongoDB aggregation framework, what it is, what benefits it of…...
python 报错问题汇总
error: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: d:\\anaconda\\envs\\yolov5\\lib\\site-packages\\ISR-2.2.0-py3.7.egg 解决方法:重启pycharm python-contrib 无法安装 opencv-contrib-python 安装包网址:安装包下载链接…...
6.5物联网RK3399项目开发实录-驱动开发之LCD显示屏使用(wulianjishu666)
90款行业常用传感器单片机程序及资料【stm32,stc89c52,arduino适用】 链接:https://pan.baidu.com/s/1M3u8lcznKuXfN8NRoLYtTA?pwdc53f LCD使用 简介 AIO-3399J开发板外置了两个LCD屏接口,一个是EDP,一个是LVDS,接口对应板…...
「Android高级工程师」BAT大厂面试基础题集合-下-Github标星6-5K
C、 com.android.provider.contact D、 com.android.provider.contacts 11.下面关于ContentProvider描述错误的是()。 A、 ContentProvider可以暴露数据 B、 ContentProvider用于实现跨程序共享数据 C、 ContentProvider不是四大组件 D、 ContentP…...
【算法】基数排序
简介 基数排序(*Radix sort)是一种非比较排序算法(non-comparative sorting algorithm)。现代计算机的基数排序算法由 计数排序 算法的开发人哈罗德H西华德(Harold H. Seward)于1954年于麻省理工大学开发。…...
2核2G服务器优惠价格轻量61元一年,CVM价格313元15个月
腾讯云2核2G服务器多少钱一年?轻量服务器61元一年,CVM 2核2G S5服务器313.2元15个月,轻量2核2G3M带宽、40系统盘,云服务器CVM S5实例是2核2G、50G系统盘。腾讯云2核2G服务器优惠活动 txybk.com/go/txy 链接打开如下图:…...
不同Python版本和wxPython版本用pyinstaller打包文件大小对比
1、确定wxPython和Python版本的对应关系 在这里可以找到Python支持的所有wxPython版本:https://pypi.tuna.tsinghua.edu.cn/simple/wxpython/ 由于Python从3.6版本开始支持f字符串、从3.9版本开始不支持Windows7操作系统,所以我仅筛选3.6-3.8之间的版本…...
【C语言】结构体详解(一)
目录 1、什么是结构体? 2、结构体成分 3、结构体变量的定义与初始化 3.1、结构体变量的三种定义方式 3.2、结构体变量的初始化 4、结构体成员的访问(两种方式) 4.1、直接访问 4.2、间接访问 5、结构的特殊声明 5.1、不完全声明(匿…...
AI时代-普通人的AI绘画工具对比(Midjouney与Stable Diffusion)
AI时代-普通人的AI绘画工具对比(Midjouney与Stable Diffusion) 前言1、基础对比Stable Diffusion(SD)SD界面安装与使用SD Midjouney(MJ) 2、硬件与运行要求对比Stable Diffusion硬件要求内存硬盘显卡 Midjo…...
【蓝桥杯】矩阵快速幂
一.快速幂概述 1.引例 1)题目描述: 求A^B的最后三位数表示的整数,A^B表示:A的B次方。 2)思路: 一般的思路是:求出A的B次幂,再取结果的最后三位数。但是由于计算机能够表示的数字…...
C语言使用STM32开发板手搓高端家居洗衣机
目录 概要 成品效果 背景概述 1.开发环境 2.主要传感器。 技术细节 1. 用户如何知道选择了何种功能 2.启动后如何进行洗衣 3.如何将洗衣机状态上传至服务器并通过APP查看 4.洗衣过程、可燃气检测、OLED屏显示、服务器通信如何并发进行 小结 概要 本文章主要是讲解如…...
【Hello,PyQt】QTextEdit和QSplider
PyQt5 是一个强大的Python库,用于创建图形用户界面(GUI)。其中,QTextEdit 控件作为一个灵活多用的组件,常用于显示和编辑多行文本内容,支持丰富的格式设置和文本操作功能。另外,QSlider 控件是一…...
【力扣】191.位 1 的个数、485.最大连续 1 的个数
191.位 1 的个数 题目描述 编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中 设置位 的个数(也被称为汉明重量)。 示例 1: 输入:n 11 输出࿱…...
蓝桥杯 java 承压计算
题目: 思路: 1:其中的数字代表金属块的重量(计量单位较大) 说明每个数字后面不一定有多少个0 2:假设每块原料的重量都十分精确地平均落在下方的两个金属块上,最后,所有的金属块的重量都严格精确地平分落在最底层的电子…...
leetcode268-Missing Number
这道题目要求缺失的数字,一般解决数组的问题,要么往排序数组,要么往双指针遍历这些方向上靠,要么往异或方向上靠,总之落点无非就只有这几个。我们要求缺失的数字,可以依次让1~n和数组元素进行异…...
【jenkins+cmake+svn管理c++项目】jenkins回传文件到svn(windows)
书接上文:创建一个项目 在经过cmakemsbuild顺利生成动态库之后,考虑到我一个项目可能会生成多个动态库,它们分散在build内的不同文件夹,我希望能将它们收拢到一个文件夹下,并将其回传到svn。 一、动态库移位—cmake实…...
数据结构·二叉树(2)
目录 1 堆的概念 2 堆的实现 2.1 堆的初始化和销毁 2.2 获取堆顶数据和堆的判空 2.3 堆的向上调整算法 2.4 堆的向下调整算法 2.4 堆的插入 2.5 删除堆顶数据 2.6 建堆 3 建堆的时间复杂度 3.1 向上建堆的时间复杂度 3.2向下建堆的时间复杂度 4 堆的排序 前言&…...
MATLAB算法实战应用案例精讲-【毕业季论文专用】人工智能视觉检测技术及其在实际应用中的挑战与前景
目录 摘要: 第一章:引言 1.1 研究背景 1.2 研究目的与意义...
Linux虚拟机环境搭建spark
Linux环境搭建Spark分为两个版本,分别是Scala版本和Python版本。 一、 安装Pyspark 本环境以 Python 环境为例。 1、下载spark 下载网址:https://archive.apache.org/dist/spark 下载安装包:根据自己环境选择合适版本,本环境…...
STL的string容器
string基本概念 string是C风格的字符串,本质上是一个类。 string 和 char* 的区别 char* 是一个指针; string是一个类,内部封装了 char* ,用来管理字符串,是一个 char* 型的容器。 特点 string内部封装了很多成员…...
国防科技大学计算机基础课程笔记02信息编码
1.机内码和国标码 国标码就是我们非常熟悉的这个GB2312,但是因为都是16进制,因此这个了16进制的数据既可以翻译成为这个机器码,也可以翻译成为这个国标码,所以这个时候很容易会出现这个歧义的情况; 因此,我们的这个国…...
盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来
一、破局:PCB行业的时代之问 在数字经济蓬勃发展的浪潮中,PCB(印制电路板)作为 “电子产品之母”,其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透,PCB行业面临着前所未有的挑战与机遇。产品迭代…...
汽车生产虚拟实训中的技能提升与生产优化
在制造业蓬勃发展的大背景下,虚拟教学实训宛如一颗璀璨的新星,正发挥着不可或缺且日益凸显的关键作用,源源不断地为企业的稳健前行与创新发展注入磅礴强大的动力。就以汽车制造企业这一极具代表性的行业主体为例,汽车生产线上各类…...
【Java_EE】Spring MVC
目录 Spring Web MVC 编辑注解 RestController RequestMapping RequestParam RequestParam RequestBody PathVariable RequestPart 参数传递 注意事项 编辑参数重命名 RequestParam 编辑编辑传递集合 RequestParam 传递JSON数据 编辑RequestBody …...
Spring Cloud Gateway 中自定义验证码接口返回 404 的排查与解决
Spring Cloud Gateway 中自定义验证码接口返回 404 的排查与解决 问题背景 在一个基于 Spring Cloud Gateway WebFlux 构建的微服务项目中,新增了一个本地验证码接口 /code,使用函数式路由(RouterFunction)和 Hutool 的 Circle…...
关键领域软件测试的突围之路:如何破解安全与效率的平衡难题
在数字化浪潮席卷全球的今天,软件系统已成为国家关键领域的核心战斗力。不同于普通商业软件,这些承载着国家安全使命的软件系统面临着前所未有的质量挑战——如何在确保绝对安全的前提下,实现高效测试与快速迭代?这一命题正考验着…...
力扣热题100 k个一组反转链表题解
题目: 代码: func reverseKGroup(head *ListNode, k int) *ListNode {cur : headfor i : 0; i < k; i {if cur nil {return head}cur cur.Next}newHead : reverse(head, cur)head.Next reverseKGroup(cur, k)return newHead }func reverse(start, end *ListNode) *ListN…...
【JavaSE】多线程基础学习笔记
多线程基础 -线程相关概念 程序(Program) 是为完成特定任务、用某种语言编写的一组指令的集合简单的说:就是我们写的代码 进程 进程是指运行中的程序,比如我们使用QQ,就启动了一个进程,操作系统就会为该进程分配内存…...
关于uniapp展示PDF的解决方案
在 UniApp 的 H5 环境中使用 pdf-vue3 组件可以实现完整的 PDF 预览功能。以下是详细实现步骤和注意事项: 一、安装依赖 安装 pdf-vue3 和 PDF.js 核心库: npm install pdf-vue3 pdfjs-dist二、基本使用示例 <template><view class"con…...
破解路内监管盲区:免布线低位视频桩重塑停车管理新标准
城市路内停车管理常因行道树遮挡、高位设备盲区等问题,导致车牌识别率低、逃费率高,传统模式在复杂路段束手无策。免布线低位视频桩凭借超低视角部署与智能算法,正成为破局关键。该设备安装于车位侧方0.5-0.7米高度,直接规避树枝遮…...
