当前位置: 首页 > news >正文

Mongo数据库 --- Mongo Pipeline

Mongo数据库 --- Mongo Pipeline

  • 什么是Mongo Pipeline
  • Mongo Pipeline常用的几个Stage
  • Explanation with example:
    • MongoDB $match
    • MongoDB $project
    • MongoDB $group
    • MongoDB $unwind
    • MongoDB $count
    • MongoDB $addFields
  • Some Query Examples
  • 在C#中使用Aggreagtion Pipeline
    • **方法一: 使用RawBsonDocument**
    • 使用 Fluent API

什么是Mongo Pipeline

  • 在MongoDB中,聚合管道(aggregation pipeline)是一种用于处理和转换数据的机制。它允许您按顺序对集合中的文档执行一系列操作,并将结果从一个阶段传递到下一个阶段。聚合管道由多个阶段组成,每个阶段在输入文档上执行特定的操作,并生成转换后的输出,作为下一个阶段的输入。
  • 聚合管道中的每个阶段接收输入文档,并应用某种操作,例如过滤、分组、投影或排序,以生成一组修改后的文档。一个阶段的输出成为下一个阶段的输入,形成了一个数据处理的管道流程.
  • 聚合管道提供了一种强大而灵活的方式来执行复杂的数据处理任务,例如过滤、分组、排序、连接和聚合数据,所有这些都可以在MongoDB查询框架内完成。它能够高效地处理大型数据集,并提供了一种方便的方式来在返回结果之前对数据进行形状和操作
  • MongoDB的聚合管道(aggregation pipeline)是在MongoDB服务器上执行的。聚合管道操作在服务器端进行,而不是将数据取出并在本地内存中执行

Mongo Pipeline常用的几个Stage

  • $match:根据指定的条件筛选文档,类似于查询中的find操作。可以使用各种条件和表达式进行匹配。
  • $project:重新塑造文档结构,包括选择特定字段、排除字段、创建计算字段、重命名字段等。还可以使用表达式进行计算和转换。
  • $group:按照指定的键对文档进行分组,并对每个组执行聚合操作,如计算总和、平均值、计数等。可以进行多字段分组和多个聚合操作。
  • $sort:根据指定的字段对文档进行排序,可以指定升序或降序排序。
  • $limit:限制返回结果的文档数量,只保留指定数量的文档。
  • $skip:跳过指定数量的文档,返回剩余的文档。
  • $unwind:将包含数组的字段拆分为多个文档,每个文档包含数组中的一个元素。这在对数组字段进行聚合操作时很有用。
  • $lookup:执行左连接操作,将当前集合中的文档与其他集合中的文档进行关联。可以根据匹配条件将相关文档合并到结果中

Explanation with example:

Example使用以下数据

//University Collection
{country : 'Spain',city : 'Salamanca',name : 'USAL',location : {type : 'Point',coordinates : [ -5.6722512,17, 40.9607792 ]},students : [{ year : 2014, number : 24774 },{ year : 2015, number : 23166 },{ year : 2016, number : 21913 },{ year : 2017, number : 21715 }]
}{country : 'Spain',city : 'Salamanca',name : 'UPSA',location : {type : 'Point',coordinates : [ -5.6691191,17, 40.9631732 ]},students : [{ year : 2014, number : 4788 },{ year : 2015, number : 4821 },{ year : 2016, number : 6550 },{ year : 2017, number : 6125 }]
}
//Course Collection
{university : 'USAL',name : 'Computer Science',level : 'Excellent'
}
{university : 'USAL',name : 'Electronics',level : 'Intermediate'
}
{university : 'USAL',name : 'Communication',level : 'Excellent'
}

MongoDB $match

  • 根据指定的条件筛选文档,类似于查询中的find操作。可以使用各种条件和表达式进行匹配。
db.universities.aggregate([{ $match : { country : 'Spain', city : 'Salamanca' } }
]).pretty()

Output:

{country : 'Spain',city : 'Salamanca',name : 'USAL',location : {type : 'Point',coordinates : [ -5.6722512,17, 40.9607792 ]},students : [{ year : 2014, number : 24774 },{ year : 2015, number : 23166 },{ year : 2016, number : 21913 },{ year : 2017, number : 21715 }]
}{country : 'Spain',city : 'Salamanca',name : 'UPSA',location : {type : 'Point',coordinates : [ -5.6691191,17, 40.9631732 ]},students : [{ year : 2014, number : 4788 },{ year : 2015, number : 4821 },{ year : 2016, number : 6550 },{ year : 2017, number : 6125 }]
}

MongoDB $project

  • 重新塑造文档结构,包括选择特定字段、排除字段、创建计算字段、重命名字段等。还可以使用表达式进行计算和转换
  • In the code that follows, please note that:
  • We must explicitly write _id : 0 when this field is not required
  • Apart from the _id field, it is sufficient to specify only those fields we need to obtain as a result of the query
db.universities.aggregate([{ $project : { _id : 0, country : 1, city : 1, name : 1 } }
]).pretty()

Output:

{ "country" : "Spain", "city" : "Salamanca", "name" : "USAL" }
{ "country" : "Spain", "city" : "Salamanca", "name" : "UPSA" }

MongoDB $group

  • 按照指定的键对文档进行分组,并对每个组执行聚合操作,如计算总和、平均值、计数等。可以进行多字段分组和多个聚合操作。
//$sum : 1 的意思是计算每个分组中document的数量,$sum : 2 则是doccument数量的两倍
db.universities.aggregate([{ $group : { _id : '$name', totaldocs : { $sum : 1 } } }
]).pretty()

Output:

{ "_id" : "UPSA", "totaldocs" : 1 }
{ "_id" : "USAL", "totaldocs" : 1 }
  • $group支持的operator
  • $count: Calculates the quantity of documents in the given group.
  • $max Displays the maximum value of a document’s field in the collection.
  • $min Displays the minimum value of a document’s field in the collection.
  • $avg Displays the average value of a document’s field in the collection.
  • $sum Sums up the specified values of all documents in the collection.
  • $push Adds extra values into the array of the resulting document.

MongoDB $unwind

  • 将包含数组的字段拆分为多个文档,每个文档包含数组中的一个元素。这在对数组字段进行聚合操作时很有用
db.universities.aggregate([{ $match : { name : 'USAL' } },{ $unwind : '$students' }
]).pretty()
  • unwind students会把每个student记录提取出来和剩下的属性拼起来变成一个独立的dcoument

Input

{country : 'Spain',city : 'Salamanca',name : 'USAL',location : {type : 'Point',coordinates : [ -5.6722512,17, 40.9607792 ]},students : [{ year : 2014, number : 24774 },{ year : 2015, number : 23166 },]
}

Output:

{"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),"country" : "Spain","city" : "Salamanca","name" : "USAL","location" : {"type" : "Point","coordinates" : [-5.6722512,17,40.9607792]},"students" : {"year" : 2014, "number" : 24774}
}
{"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),"country" : "Spain","city" : "Salamanca","name" : "USAL","location" : {"type" : "Point","coordinates" : [-5.6722512,17,40.9607792]},"students" : {"year" : 2015,"number" : 23166}
}

MongoDB $count

  • The $count stage provides an easy way to check the number of documents obtained in the output of the previous stages of the pipeline
db.universities.aggregate([{ $unwind : '$students' },{ $count : 'total_documents' }
]).pretty()

Output:

{ "total_documents" : 8 }

MongoDB $addFields

  • It is possible that you need to make some changes to your output in the way of new fields. In the next example, we want to add the year of the foundation of the university.
  • addField 不会修改数据库
db.universities.aggregate([{ $match : { name : 'USAL' } },{ $addFields : { foundation_year : 1218 } }
]).pretty()
{"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),"country" : "Spain","city" : "Salamanca","name" : "USAL","location" : {"type" : "Point","coordinates" : [-5.6722512,17,40.9607792]},"students" : [{"year" : 2014,"number" : 24774},{"year" : 2015,"number" : 23166},{"year" : 2016,"number" : 21913},{"year" : 2017,"number" : 21715}],"foundation_year" : 1218
}

Some Query Examples

db.collection.aggregate([{ $match: { age: { $gt: 30 } } }
])
db.collection.aggregate([{ $group: { _id: "$category", total: { $sum: "$quantity" } } }
])
//This example selects the "name" field and creates a new field called "fullName" 
//by concatenating the "firstName" and "lastName" fields.
db.collection.aggregate([{ $project: { _id: 0, name: 1, fullName: { $concat: ["$firstName", " ", "$lastName"] } } }
])
//This example sorts documents in descending order based on the "age" field.
db.collection.aggregate([{ $sort: { age: -1 } }
])
//This example limits the output to only the first 10 documents.
db.collection.aggregate([{ $limit: 10 }
])

在C#中使用Aggreagtion Pipeline

方法一: 使用RawBsonDocument

BsonDocument pipelineStage1 = new BsonDocument{{"$match", new BsonDocument{{ "username", "nraboy" }}}
};BsonDocument pipelineStage2 = new BsonDocument{{ "$project", new BsonDocument{{ "_id", 1 },{ "username", 1 },{ "items", new BsonDocument{{"$map", new BsonDocument{{ "input", "$items" },{ "as", "item" },{"in", new BsonDocument{{"$convert", new BsonDocument{{ "input", "$$item" },{ "to", "objectId" }}}}}}}}}}}
};BsonDocument pipelineStage3 = new BsonDocument{{"$lookup", new BsonDocument{{ "from", "movies" },{ "localField", "items" },{ "foreignField", "_id" },{ "as", "movies" }}}
};BsonDocument pipelineStage4 = new BsonDocument{{ "$unwind", "$movies" }
};BsonDocument pipelineStage5 = new BsonDocument{{"$group", new BsonDocument{{ "_id", "$_id" },{ "username", new BsonDocument{{ "$first", "$username" }} },{ "movies", new BsonDocument{{ "$addToSet", "$movies" }}}}}
};BsonDocument[] pipeline = new BsonDocument[] { pipelineStage1, pipelineStage2, pipelineStage3, pipelineStage4, pipelineStage5 
};List<BsonDocument> pResults = playlistCollection.Aggregate<BsonDocument>(pipeline).ToList();foreach(BsonDocument pResult in pResults) {Console.WriteLine(pResult);
}

使用 Fluent API

var pResults = playlistCollection.Aggregate().Match(new BsonDocument{{ "username", "nraboy" }}).Project(new BsonDocument{{ "_id", 1 },{ "username", 1 },{"items", new BsonDocument{{"$map", new BsonDocument{{ "input", "$items" },{ "as", "item" },{"in", new BsonDocument{{"$convert", new BsonDocument{{ "input", "$$item" },{ "to", "objectId" }}}}}}}}}}).Lookup("movies", "items", "_id", "movies").Unwind("movies").Group(new BsonDocument{{ "_id", "$_id" },{"username", new BsonDocument{{ "$first", "$username" }}},{"movies", new BsonDocument{{ "$addToSet", "$movies" }}}}).ToList();foreach(var pResult in pResults) {Console.WriteLine(pResult);
}

相关文章:

Mongo数据库 --- Mongo Pipeline

Mongo数据库 --- Mongo Pipeline 什么是Mongo PipelineMongo Pipeline常用的几个StageExplanation with example:MongoDB $matchMongoDB $projectMongoDB $groupMongoDB $unwindMongoDB $countMongoDB $addFields Some Query Examples在C#中使用Aggreagtion Pipeline**方法一: …...

Adobe Illustrator 2024 安装教程与下载分享

介绍一下 下载直接看文章末尾 Adobe Illustrator 是一款由Adobe Systems开发的矢量图形编辑软件。它广泛应用于创建和编辑矢量图形、插图、徽标、图标、排版和广告等领域。以下是Adobe Illustrator的一些主要特点和功能&#xff1a; 矢量绘图&#xff1a;Illustrator使用矢量…...

javax.xml.ws.soap.SOAPFaultException: ZONE_OFFSET

javax.xml.ws.soap.SOAPFaultException 表示 SOAP 调用过程中发生了错误&#xff0c;并且服务端返回了一个 SOAP Fault。 错误信息中提到的 ZONE_OFFSET 可能指的是时区偏移量。在日期和时间处理中&#xff0c;时区偏移量是指格林威治标准时间 (GMT) 的偏移量。如果服务期望特…...

常用的数据结构

队列(FIFO) 栈(LIFO) 链表 hash表 hash冲突处理 开放式寻址 线性探测 表示依次检查索引为 hash(key) + 1、hash(key) + 2 ... 的位置。i 是冲突后的探查步数。公式:hash(i) = (hash(key) + i) % TableSize二次探查 规则:冲突后探查的步长是平方递增的,例如,检查位置为 hash…...

javaweb-day01-html和css初识

html:超文本标记语言 CSS&#xff1a;层叠样式表 1.html实现新浪新闻页面 1.1 标题排版 效果图&#xff1a; 1.2 标题颜色样式 1.3 标签内颜色样式 1.4设置超链接 1.5 正文排版 1.6 页面布局–盒子 &#xff08;1&#xff09;盒子模型 &#xff08;2&#xff09;页面布局…...

C++11特性(详解)

目录 1.C11简介 2.列表初始化 3.声明 1.auto 2.decltype 3.nullptr 4.范围for循环 5.智能指针 6.STL的一些变化 7.右值引用和移动语义 1.左值引用和右值引用 2.左值引用和右值引用的比较 3.右值引用的使用场景和意义 4.右值引用引用左值及其一些更深入的使用场景分…...

基于Springboot的心灵治愈交流平台系统的设计与实现

基于Springboot的心灵治愈交流平台系统 介绍 基于Springboot的心灵治愈交流平台系统&#xff0c;后端框架使用Springboot和mybatis&#xff0c;前端框架使用Vuehrml&#xff0c;数据库使用mysql&#xff0c;使用B/S架构实现前台用户系统和后台管理员系统&#xff0c;和不同级别…...

初识java(2)

大家好&#xff0c;今天我们来讲讲java中的数据类型。 java跟我们的c语言的数据类型有一些差别&#xff0c;那么接下来我们就来看看。 一.字面常量&#xff0c;其中&#xff1a;199&#xff0c;3.14&#xff0c;‘a’&#xff0c;true都是常量将其称为字面常量。&#xff08;…...

AIGC--AIGC与人机协作:新的创作模式

AIGC与人机协作&#xff1a;新的创作模式 引言 人工智能生成内容&#xff08;AIGC&#xff09;正在以惊人的速度渗透到创作的各个领域。从生成文本、音乐、到图像和视频&#xff0c;AIGC使得创作过程变得更加快捷和高效。然而&#xff0c;AIGC并非完全取代了人类的创作角色&am…...

Wonder3D本地部署到算家云搭建详细教程

Wonder3D简介 Wonder3D仅需2至3分钟即可从单视图图像中重建出高度详细的纹理网格。Wonder3D首先通过跨域扩散模型生成一致的多视图法线图与相应的彩色图像&#xff0c;然后利用一种新颖的法线融合方法实现快速且高质量的重建。 本文详细介绍了在算家云搭建Wonder3D的流程以及…...

【设计模式】【行为型模式(Behavioral Patterns)】之状态模式(State Pattern)

1. 设计模式原理说明 状态模式&#xff08;State Pattern&#xff09; 是一种行为设计模式&#xff0c;它允许对象在其内部状态发生变化时改变其行为。这个模式的核心思想是使用不同的类来表示不同的状态&#xff0c;每个状态类都封装了与该状态相关的特定行为。当对象的状态发…...

QML学习 —— 34、视频媒体播放器(附源码)

效果 说明 您可以单独使用MediaPlayer播放音频内容(如音频),也可以将其与VideoOutput结合使用以渲染视频。VideoOutput项支持未转换、拉伸和均匀缩放的视频演示。有关拉伸均匀缩放演示文稿的描述,请参见fillMode属性描述。 播放可能出错问题 出现的问题:      DirectS…...

【深度学习|特征增强模块】FFN(前馈神经网络)和E_FFN(增强型前馈神经网络)是transformer特征增强的重要组成部分!

【深度学习|特征增强模块】FFN&#xff08;前馈神经网络&#xff09;和E_FFN&#xff08;增强型前馈神经网络&#xff09;是transformer特征增强的重要组成部分&#xff01; 【深度学习|特征增强模块】FFN&#xff08;前馈神经网络&#xff09;和E_FFN&#xff08;增强型前馈神…...

【Qt】控件7

1.QTextEdit的简单使用 使用简单的QTextEdit,获取到的内容显示到标签上 使用textChanged信号 在槽函数中需要获取QTextEdit的内容&#xff0c;对应操作是&#xff1a; QString curorui->textEdit->toPlainText();然后显示到标签上&#xff0c;对应操作是&#xff1a; …...

F12抓包14_修改网页图片网页保存到本地

课程大纲 1、修改网页图片&#xff08;2种方式二选一&#xff09; 修改网页图片&#xff0c;需要定位到图片标签&#xff0c;修改<img>标签的属性。2种方法&#xff1a; 1. 修改为网络图片url。缺点&#xff1a;url失效&#xff0c;图片无法显示。 2. 修改为图片base64&a…...

源代码检测,内附实际案例

源代码安全审计是依据国标GB/T 34944-2017、GB/T 34944-2017&#xff0c;结合专业源代码扫描工具对各种程序语言编写的源代码进行安全审计。能够为客户提供包括安全编码规范咨询、源代码安全现状评测、定位源代码中存在的安全漏洞、分析漏洞风险、给出修改建议等一系列服务。 源…...

1138:将字符串中的小写字母转换成大写字母

【题目描述】 给定一个字符串&#xff0c;将其中所有的小写字母转换成大写字母。 【输入】 输入一行&#xff0c;包含一个字符串&#xff08;长度不超过100&#xff0c;可能包含空格&#xff09;。 【输出】 输出转换后的字符串。 【输入样例】 helloworld123Ha 【输出样例】…...

《C++ 人工智能模型邂逅云平台:集成之路的策略与要点全解析》

在当今数字化浪潮汹涌澎湃的时代&#xff0c;人工智能无疑是引领技术变革的核心力量。而 C以其卓越的性能和高效的资源利用&#xff0c;成为开发人工智能模型的有力武器。与此同时&#xff0c;云平台所提供的强大计算能力、灵活的存储资源以及便捷的服务部署&#xff0c;为人工…...

【ArcGISPro】Sentinel-2数据处理

错误 默认拉进去只组织了4个波段,但是实际有12个波段 解决方案 数据下载 Sentinel-2 数据下载-CSDN博客 数据处理 数据查看 创建镶嵌数据集 在数据管理工具箱中找到创建镶嵌数据集...

Unity中的简易TCP服务器/客户端

在本文中&#xff0c;我将向你介绍一个在Unity中实现的简单TCP服务器脚本,和一个简单的客户端脚本. 脚本 MyTcpServer 允许Unity应用创建一个TCP服务器&#xff0c;监听客户端的连接、异步处理客户端消息&#xff0c;并通过事件与Unity应用中的其他模块进行通信。 MyTcpServe…...

从仿真到PCB:基于74LS系列芯片的十字路口交通灯系统实战设计

1. 项目背景与设计目标 十字路口交通灯控制系统是数字电路课程的经典实践项目。记得我第一次接触这个课题时&#xff0c;既兴奋又忐忑——兴奋的是终于能把课本上的与非门、触发器应用到真实场景&#xff0c;忐忑的是从仿真到实物可能存在的各种"坑"。这个基于74LS系…...

分数阶傅里叶变换在声纳阵列分析中的应用与优化

1. 分数阶傅里叶变换在声纳阵列分析中的核心价值在水下声学工程领域&#xff0c;准确计算声纳阵列的辐射模式一直是个技术难点。传统FFT算法虽然计算效率高&#xff0c;但在处理特定方位角的辐射特性时存在明显的精度局限。2005年日本防卫厅技术研究本所的这项研究&#xff0c;…...

别再硬改CSS了!ElementUI el-table透明背景的3种正确姿势(含Vue2/Vue3避坑指南)

别再硬改CSS了&#xff01;ElementUI el-table透明背景的3种正确姿势&#xff08;含Vue2/Vue3避坑指南&#xff09; 在深色主题或背景融合的现代Web应用中&#xff0c;ElementUI的el-table组件默认的白色背景常常成为视觉设计的绊脚石。许多开发者第一反应是直接修改CSS文件&am…...

【研报 A109】2026年脑机接口产业化专题报告:首个侵入式产品获批,医保完成赋码

摘要&#xff1a;脑机接口行业正迎来产业化应用的关键元年&#xff0c;2026年行业正式从实验室研究走向规模化商业化落地&#xff0c;当前行业处于导入期尾端、爆发前夜&#xff0c;非侵入式与半侵入式路径已率先打通商业化通道&#xff0c;侵入式则处于临床验证阶段。政策端&a…...

GD32F303硬件I2C实战:手把手教你用AT24C02 EEPROM存储和读取设备配置参数

GD32F303硬件I2C实战&#xff1a;构建工业级参数存储系统 在嵌入式设备开发中&#xff0c;系统参数的持久化存储是个看似简单却暗藏玄机的需求。想象一下&#xff0c;当你的智能温控器经历突然断电后&#xff0c;所有用户设置的日程和偏好全部归零——这种体验足以让产品口碑崩…...

【STM32H7实战】HRTIM高分辨率定时器在数字电源与电机控制中的高级应用与HAL库配置

1. HRTIM高分辨率定时器概述 HRTIM&#xff08;High-Resolution Timer&#xff09;是STM32H7系列中一个强大的定时器外设&#xff0c;专为数字电源转换、电机控制等高性能实时控制场景设计。相比普通定时器&#xff0c;它的分辨率高达184ps&#xff08;在400MHz主频下&#xff…...

BurstGPT:大语言模型驱动高性能计算,实现自然语言科学仿真

1. 项目概述&#xff1a;当大语言模型遇上高性能计算最近在AI和HPC&#xff08;高性能计算&#xff09;的交叉领域&#xff0c;一个名为BurstGPT的项目引起了我的注意。乍一看这个标题&#xff0c;你可能会觉得有点“缝合怪”的味道——Burst通常指代计算资源的突发式使用或高性…...

BGA虚焊别头疼!从焊膏印刷到回流焊曲线,一份保姆级的SMT工艺避坑指南

BGA虚焊别头疼&#xff01;从焊膏印刷到回流焊曲线&#xff0c;一份保姆级的SMT工艺避坑指南 在SMT产线上&#xff0c;BGA虚焊问题就像个幽灵&#xff0c;时不时冒出来折腾工程师。上周产线刚报修一批主板&#xff0c;X光下那些不规则焊点像极了抽象派画作——可惜客户要的是工…...

紫光同创Logos系列FPGA实战:BGA封装PCB布局与Fanout布线避坑指南(附示意图)

紫光同创Logos系列FPGA实战&#xff1a;BGA封装PCB布局与Fanout布线避坑指南 第一次拿到紫光同创Logos系列FPGA的BGA封装芯片时&#xff0c;那种密密麻麻的焊盘阵列确实会让人头皮发麻。特别是FBG256和FBG484这类高密度封装&#xff0c;如何在有限的空间内完成高质量的Fanout布…...

英雄联盟Akari助手:智能游戏伴侣让你的排位赛效率提升10倍

英雄联盟Akari助手&#xff1a;智能游戏伴侣让你的排位赛效率提升10倍 【免费下载链接】League-Toolkit An all-in-one toolkit for LeagueClient. Gathering power &#x1f680;. 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 还在为英雄联盟中繁琐的…...