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);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/60888.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

银行卡 OCR 识别 API 接口的发展前景

随着智能手机的广泛普及以及互联网的迅猛发展&#xff0c;“互联网 ” 时代的移动支付已然开启了智慧生活的崭新蓝图。移动支付要求进行实名认证并绑定银行卡&#xff0c;然而传统的手工输入银行卡号不但速度缓慢、容易出错&#xff0c;还极大地降低了用户体验。银行卡 OCR 识别…

华为OD机试真题---智能驾驶

华为OD机试中的“智能驾驶”题目是一道涉及广度优先搜索&#xff08;BFS&#xff09;算法运用的题目。以下是对该题目的详细解析&#xff1a; 一、题目描述 有一辆汽车需要从m * n的地图的左上角&#xff08;起点&#xff09;开往地图的右下角&#xff08;终点&#xff09;&a…

Redis与MySQL如何保证数据一致性

Redis与MySQL如何保证数据一致性 简单来说 该场景主要发生在读写并发进行时&#xff0c;才会发生数据不一致。 主要流程就是要么先操作缓存&#xff0c;要么先操作Redis&#xff0c;操作也分修改和删除。 一般修改要执行一系列业务代码&#xff0c;所以一般直接删除成本较低…

Linux宝塔部署wordpress网站更换服务器IP后无法访问管理后台和打开网站页面显示错乱

一、背景&#xff1a; wordpress网站搬家&#xff0c;更换服务器IP后&#xff0c;如果没有域名时&#xff0c;使用服务器IP地址无法访问管理后台和打开网站页面显示错乱。 二、解决方法如下&#xff1a; 1.wordpress搬家后&#xff0c;在新服务器上&#xff0c;新建站点时&am…

探秘嵌入式位运算:基础与高级技巧

目录 一、位运算基础知识 1.1. 位运算符 1.1.1. 与运算&#xff08;&&#xff09; 1.1.2. 或运算&#xff08;|&#xff09; 1.1.3. 异或运算&#xff08;^&#xff09; 1.1.4. 取反运算&#xff08;~&#xff09; 1.1.5. 双重按位取反运算符&#xff08;~~&#xf…

MySQL底层概述—3.InnoDB线程模型

大纲 1.InnoDB的线程模型 2.IO Thread 3.Purge Thread 4.Page Cleaner Thread 5.Master Thread 1.InnoDB的线程模型 InnoDB存储引擎是多线程的模型&#xff0c;因此其后台有多个不同的后台线程&#xff0c;负责处理不同的任务。 后台线程的作用一&#xff1a;负责刷新内存…

充满智慧的埃塞俄比亚狼

非洲的青山 随着地球温度上升&#xff0c;贝尔山顶峰的冰川消失殆尽&#xff0c;许多野生动物移居到海拔3000米以上的高原上生活&#xff0c;其中就包括埃塞俄比亚狼。埃塞俄比亚狼是埃塞俄比亚特有的动物&#xff0c;总数不到500只&#xff0c;为“濒危”物种。 埃塞俄比亚狼…

pikachu平台xss漏洞详解

声明&#xff1a;文章只是起演示作用&#xff0c;所有涉及的网站和内容&#xff0c;仅供大家学习交流&#xff0c;如有任何违法行为&#xff0c;均和本人无关&#xff0c;切勿触碰法律底线 文章目录 概述&#xff1a;什么是xss一、反射型XSS1. get2. post 二、存储型XSS三、DOM…

Easyexcel(7-自定义样式)

相关文章链接 Easyexcel&#xff08;1-注解使用&#xff09;Easyexcel&#xff08;2-文件读取&#xff09;Easyexcel&#xff08;3-文件导出&#xff09;Easyexcel&#xff08;4-模板文件&#xff09;Easyexcel&#xff08;5-自定义列宽&#xff09;Easyexcel&#xff08;6-单…

FFN层,全称为Feed-Forward Network层;Layer Normalization;Softmax;

目录 FFN层,全称为Feed-Forward Network层 Layer Normalization 操作步骤 归一化和Softmax 归一化解决量纲问题 归一化(Normalization) Softmax FFN层,全称为Feed-Forward Network层 是Transformer架构中的一个关键组件。它本质上是一个简单的多层感知机(MLP),用…

Android OTA 更新面试题及参考答案

目录 什么是 OTA 更新? 什么是 OTA 更新的主要目的? Android OTA 更新是如何与系统的分区机制相互配合的? 什么是 A/B 分区更新,它的优势是什么? Android 系统中的 “System Partition” 和 “Vendor Partition” 有什么区别? 请详细阐述 Android OTA 更新的基本原…

网络研讨会——如何使用Figma、Canva或Sketch设计Delphi移动应用程序

2024年11月30日星期六 - 北京午夜12点 如何使用Figma、Canva或Sketch设计Delphi移动应用程序 专业设计应用程序Figma、Sketch和Canva有大量优秀的应用程序设计等着你去实现。我们看看有什么可用的&#xff0c;并使用一些最好的设计来创建应用程序。。。 立即报名免费在线研讨会…

通用网络安全设备之【防火墙】

概念&#xff1a; 防火墙&#xff08;Firewall&#xff09;&#xff0c;也称防护墙&#xff0c;它是一种位于内部网络与外部网络之间的网络安全防护系统&#xff0c;是一种隔离技术&#xff0c;允许或是限制传输的数据通过。 基于 TCP/IP 协议&#xff0c;主要分为主机型防火…

对于GC方面,在使用Elasticsearch时要注意什么?

大家好&#xff0c;我是锋哥。今天分享关于【对于GC方面&#xff0c;在使用Elasticsearch时要注意什么&#xff1f;】面试题。希望对大家有帮助&#xff1b; 对于GC方面&#xff0c;在使用Elasticsearch时要注意什么&#xff1f; 1000道 互联网大厂Java工程师 精选面试题-Java…

[仓颉Cangjie刷题模板] 优先队列(含小顶堆实现)

[TOC]([仓颉Cangjie刷题模板] 优先队列(含小顶堆实现) ) 一、 算法&数据结构 1. 描述 堆是一个可以维护实时最大/最小值的数据结构&#xff0c;相比treeset等常数优很多。 常用于维护一组数据的极值贪心问题。2. 复杂度分析 初始化O(n)查询O(1)修改O(lgn) 3. 常见应用…

解决 MySQL 5.7 安装中的常见问题及解决方案

目录 前言1. 安装MySQL 5.7时的常见错误分析1.1 错误原因及表现1.2 错误的根源 2. 解决方案2.1 修改YUM仓库配置2.2 重新尝试安装2.3 处理GPG密钥错误2.4 解决依赖包问题 3. 安装成功后的配置3.1 启动MySQL服务3.2 获取临时密码3.3 修改root密码 4. 结语 前言 在Linux服务器上…

计算机网络 网络安全基础——针对实习面试

目录 网络安全基础你了解被动攻击吗&#xff1f;你了解主动攻击吗&#xff1f;你了解病毒吗&#xff1f;说说基本的防护措施和安全策略&#xff1f; 网络安全基础 网络安全威胁是指任何可能对网络系统造成损害的行为或事件。这些威胁可以是被动的&#xff0c;也可以是主动的。…

oracle小技巧-解决特殊密码字符而导致的exp错误

在使用oracle数据库的时候&#xff0c;我们经常会利用exp工具对某些表进行导出。但有些时候&#xff0c;因我们用户密码为安全性设有特殊字符&#xff0c;导致exp导出时候报&#xff1a;“EXP-00056和ORA-12154”&#xff0c;今天我们就分享下如何通过设置符号隔离的小技巧解决…

【在 PyTorch 中使用 tqdm 显示训练进度条,并解决常见错误TypeError: ‘module‘ object is not callable】

在 PyTorch 中使用 tqdm 显示训练进度条&#xff0c;并解决常见错误TypeError: module object is not callable 在进行深度学习模型训练时&#xff0c;尤其是在处理大规模数据时&#xff0c;实时了解训练过程中的进展是非常重要的。为了实现这一点&#xff0c;我们可以使用 tq…

Taro 鸿蒙技术内幕系列(三) - 多语言场景下的通用事件系统设计

基于 Taro 打造的京东鸿蒙 APP 已跟随鸿蒙 Next 系统公测&#xff0c;本系列文章将深入解析 Taro 如何实现使用 React 开发高性能鸿蒙应用的技术内幕 背景 在鸿蒙生态系统中&#xff0c;虽然原生应用通常基于 ArkTS 实现&#xff0c;但在实际研发过程中发现&#xff0c;使用 C…