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

MongoDB - 聚合操作符 $eq、$gte、$in、$sum、$avg

文章目录

    • 1. $eq
    • 2. $gte
    • 3. $in
    • 4. $sum
    • 5. $avg

1. $eq

$eq比较两个值并返回:true (当值相等时)|false(当值相等时)

{ $eq: [ <expression1>, <expression2> ] }

构造测试数据:

db.inventory.drop()db.inventory.insertMany({{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
})

以下操作使用 $eq 操作符来判断 qty 是否等于 250

db.inventory.aggregate([{$project:{item: 1,qty: 1,qtyEq250: { $eq: [ "$qty", 250 ] },_id: 0}}]
)
// 1
{"item": "abc1","qty": 300,"qtyEq250": false
}// 2
{"item": "abc2","qty": 200,"qtyEq250": false
}// 3
{"item": "xyz1","qty": 250,"qtyEq250": true
}// 4
{"item": "VWZ1","qty": 300,"qtyEq250": false
}// 5
{"item": "VWZ2","qty": 180,"qtyEq250": false
}
//输入文档实体类
@Data
@Document(collection = "inventory")
public class Inventory {private int _id;private String item;private String description;private int qty;
}//输出文档实体类
@Data
public class AggregationResult {private String item;private String qty;private Boolean qtyEq250;
}//执行聚合操作
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void queryTest() {// $project 聚合阶段ProjectionOperation projectionOperation = Aggregation.project("item", "qty").andExclude("_id").andExpression("qty==250").as("qtyEq250");Aggregation aggregation = Aggregation.newAggregation(projectionOperation);AggregationResults<AggregationResult> aggregate = mongoTemplate.aggregate(aggregation, Inventory.class, AggregationResult.class);List<AggregationResult> mappedResults = aggregate.getMappedResults();mappedResults.forEach(System.out::println);//AggregationResult(item=abc1, qty=300.0, qtyEq250=false)//AggregationResult(item=abc2, qty=200.0, qtyEq250=false)//AggregationResult(item=xyz1, qty=250.0, qtyEq250=true)//AggregationResult(item=VWZ1, qty=300.0, qtyEq250=false)//AggregationResult(item=VWZ2, qty=180.0, qtyEq250=false)}
}

2. $gte

$gt 比较两个值并返回:true(当第一个值大于第二个值时),false(当第一个值小于或者等于第二个值时)

{ $gt: [ <expression1>, <expression2> ] }

构造测试数据:

db.inventory.drop()db.inventory.insertMany([{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
])

以下操作使用 $gt 操作符来判断 qty 是否大于 250

db.inventory.aggregate([{$project:{_id: 0,item: 1,qty: 1,qtyGt250: { $gt: [ "$qty", 250 ] }}}]
)
//输入文档实体类
@Data
@Document(collection = "inventory")
public class Inventory {private int _id;private String item;private String description;private int qty;
}//输出文档实体类
@Data
public class AggregationResult {private String item;private String qty;private Boolean qtyGt250;
}//执行聚合操作
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void queryTest() {//$project聚合阶段ProjectionOperation projectionOperation = Aggregation.project("item", "qty").andExclude("_id").andExpression("qty>250").as("qtyGt250");//组合聚合阶段Aggregation aggregation = Aggregation.newAggregation(projectionOperation);//执行聚合阶段AggregationResults<AggregationResult> aggregationResults = mongoTemplate.aggregate(aggregation, Inventory.class, AggregationResult.class);List<AggregationResult> mappedResults = aggregationResults.getMappedResults();//打印mappedResults.forEach(System.out::println);//AggregationResult(item=abc1, qty=300.0, qtyGt250=true)//AggregationResult(item=abc2, qty=200.0, qtyGt250=false)//AggregationResult(item=xyz1, qty=250.0, qtyGt250=false)//AggregationResult(item=VWZ1, qty=300.0, qtyGt250=true)//AggregationResult(item=VWZ2, qty=180.0, qtyGt250=false)}
}

3. $in

$in 返回一个布尔值,它可表示指定的值是否在数组中。

{ $in: [ <expression>, <array expression> ] }
例子结果
{ $in: [ 2, [ 1, 2, 3 ] ] }true
{ $in: [ "abc", [ "xyz", "abc" ] ] }true
{ $in: [ "xy", [ "xyz", "abc" ] ] }false
{ $in: [ [ "a" ], [ "a" ] ] }false
{ $in: [ [ "a" ], [ [ "a" ] ] ] }true
{ $in: [ /^a/, [ "a" ] ] }false
{ $in: [ /^a/, [ /^a/ ] ] }true

构造测试数据:

db.stores.drop()db.stores.insertMany([{ "_id" : 1, "location" : "上海", "fruits" : [ "apples", "oranges", "bananas" ] },{ "_id" : 2, "location" : "北京", "fruits" : [ "bananas", "pears", "grapes" ] },{ "_id" : 3, "location" : "南京", "fruits" : [ "cantaloupes", "watermelons", "apples" ] }
])

以下聚合操作查看每个文档中的 fruits 数组,并确定是否存在字符串 bananas

db.stores.aggregate([// $project聚合阶段:将文档中的location字段重命名为 store location字段{$project: {"store_location" : "$location","has_bananas" : {$in: [ "bananas", "$fruits" ]}}}
])
// 1
{"_id": 1,"store_location": "上海","has_bananas": true
}// 2
{"_id": 2,"store_location": "北京","has_bananas": true
}// 3
{"_id": 3,"store_location": "南京","has_bananas": false
}

4. $sum

当用作累加器时,$sum 的语法如下:

{ $sum: <expression> }

构造测试数据:

db.students.drop()db.students.insertMany([{ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "finalScore": 80, "midtermScore": 75 },{ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "finalScore": 95, "midtermScore": 80 },{ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "finalScore": 78, "midtermScore": 70 }
])

计算测验总分数、实验总分数以及期末和期中考试的总分数:

db.students.aggregate([{$project: {quizTotal: { $sum: "$quizzes"},labTotal: { $sum: "$labs" },examTotal: { $sum: [ "$finalScore", "$midtermScore" ] }}}
])
// 1
{"_id": 1,"quizTotal": 23,"labTotal": 13,"examTotal": 155
}// 2
{"_id": 2,"quizTotal": 19,"labTotal": 16,"examTotal": 175
}// 3
{"_id": 3,"quizTotal": 14,"labTotal": 11,"examTotal": 148
}
// 输入文档实体类
@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> quizzes;private List<Integer> labs;private int finalScore;private int midtermScore;
}// 输出文档实体类
@Data
public class AggregationResult {private int _id;private int quizTotal;private int labTotal;private int examTotal;
}// 执行聚合操作
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void queryTest() {//$project聚合阶段ProjectionOperation project = Aggregation.project().andExpression("{$sum: '$quizzes'}").as("quizTotal").andExpression("{$sum: '$labs'}").as("labTotal").andExpression("$finalScore + $midtermScore").as("examTotal");//组合聚合阶段Aggregation aggregation = Aggregation.newAggregation(project);//执行聚合阶段AggregationResults<AggregationResult> aggregationResults = mongoTemplate.aggregate(aggregation, Student.class, AggregationResult.class);List<AggregationResult> mappedResults = aggregationResults.getMappedResults();//打印mappedResults.forEach(System.out::println);//AggregationResult(_id=1, quizTotal=23, labTotal=13, examTotal=155)//AggregationResult(_id=2, quizTotal=19, labTotal=16, examTotal=175)//AggregationResult(_id=3, quizTotal=14, labTotal=11, examTotal=148)}
}

5. $avg

db.sales.drop()db.sales.insertMany([{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2) },{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1) },{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5) },{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10) },{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10) }
])

按照 item 字段对文档进行分组,以下操作使用 $avg 累加器来计算每组的平均金额和平均数量:

db.sales.aggregate([{$group:{_id: "$item",avgAmount: { $avg: { $multiply: [ "$price", "$quantity" ] } },avgQuantity: { $avg: "$quantity" }}}]
)
// 输入文档实体类
@Data
@Document(collection = "sales")
public class Sales {@Idprivate int id;private String item;private int price;private int quantity;
}// 输出文档实体类
@Data
public class AggregationResult {private int _id;private int avgAmount;private int avgQuantity;
}// 执行聚合操作
@Test
public void queryTest() {//$group聚合阶段GroupOperation groupOperation = Aggregation.group("item").avg(ArithmeticOperators.Multiply.valueOf("price").multiplyBy("quantity")).as("avgAmount").avg("quantity").as("avgQuantity");//组合聚合阶段Aggregation aggregation = Aggregation.newAggregation(groupOperation);//执行聚合阶段AggregationResults<AggregationResult> aggregationResults = mongoTemplate.aggregate(aggregation, Sales.class, AggregationResult.class);List<AggregationResult> mappedResults = aggregationResults.getMappedResults();//打印mappedResults.forEach(System.out::println);//AggregationResult(_id=0, avgAmount=3512, avgQuantity=8)
}

相关文章:

MongoDB - 聚合操作符 $eq、$gte、$in、$sum、$avg

文章目录 1. $eq2. $gte3. $in4. $sum5. $avg 1. $eq $eq比较两个值并返回&#xff1a;true &#xff08;当值相等时&#xff09;|false&#xff08;当值不相等时&#xff09; { $eq: [ <expression1>, <expression2> ] }构造测试数据&#xff1a; db.inventory…...

C语言 | Leetcode C语言题解之第279题完全平方数

题目&#xff1a; 题解&#xff1a; // 判断是否为完全平方数 bool isPerfectSquare(int x) {int y sqrt(x);return y * y x; }// 判断是否能表示为 4^k*(8m7) bool checkAnswer4(int x) {while (x % 4 0) {x / 4;}return x % 8 7; }int numSquares(int n) {if (isPerfect…...

在appium中,如何通过匹配图片来进行断言?

在Appium中进行图片匹配断言&#xff0c;可以使用OpenCV来实现。以下是使用Appium和OpenCV进行图片匹配断言的示例代码。 首先&#xff0c;需要确保安装了必要的库&#xff1a; pip install opencv-python-headless pip install opencv-python pip install numpy然后&#xf…...

昇思25天学习打卡营第21天|CV-Shufflenet图像分类

打卡 目录 打卡 ShuffleNet 网络介绍 ShuffleNet 模型架构 Pointwise Group Convolution Channel Shuffle ShuffleNet模块 ShuffleNet 模块代码 构建ShuffleNet网络 模块代码 模型训练和评估 模型训练 模型评估 模型预测 ShuffleNet 网络介绍 ShuffleNetV1是旷视科…...

python 图片转文字、语音转文字、文字转语音保存音频并朗读

一、python图片转文字 1、引言 pytesseract是基于Python的OCR工具&#xff0c; 底层使用的是Google的Tesseract-OCR 引擎&#xff0c;支持识别图片中的文字&#xff0c;支持jpeg, png, gif, bmp, tiff等图片格式 2、环境配置 python3.6PIL库安装Google Tesseract OCR 3、安…...

SSRF (服务端请求伪造)

&#x1f3bc;个人主页&#xff1a;金灰 &#x1f60e;作者简介:一名简单的大一学生;易编橙终身成长社群的嘉宾.✨ 专注网络空间安全服务,期待与您的交流分享~ 感谢您的点赞、关注、评论、收藏、是对我最大的认可和支持&#xff01;❤️ &#x1f34a;易编橙终身成长社群&#…...

SQL中的LEFT JOIN、RIGHT JOIN和INNER JOIN

在SQL中&#xff0c;JOIN操作是连接两个或多个数据库表&#xff0c;并根据两个表之间的共同列&#xff08;通常是主键和外键&#xff09;返回数据的重要方法。其中&#xff0c;LEFT JOIN&#xff08;左连接&#xff09;、RIGHT JOIN&#xff08;右连接&#xff09;和INNER JOIN…...

[网鼎杯 2020 朱雀组]Nmap(详细解读版)

这道题考察nmap的一些用法,以及escapeshellarg和escapeshellcmd两个函数的绕过&#xff0c;可以看这里PHP escapeshellarg()escapeshellcmd() 之殇 (seebug.org) 两种解题方法&#xff1a; 第一种通过nmap的-iL参数读取扫描一个文件到指定文件中第二种是利用nmap的参数写入we…...

【React】详解“最新”和“最热”切换与排序

文章目录 一、基本概念和初始化二、切换与排序功能的实现1. 函数定义和参数2. 设置活动 Tab3. 定义新列表变量4. 根据排序类型处理列表4.1 按时间降序排序4.2 按点赞数降序排序 5. 更新评论列表 三、渲染导航 Tab 和评论列表1. map 方法2. key 属性3. className 动态赋值4. onC…...

BUUCTF [MRCTF2020]Ezpop

这道题对于刚接触到pop链的我直接把我整懵了&#xff0c;一边看着魔术方法一边分析 魔术方法可以看这里PHP 魔术方法 - 简介 - PHP 魔术方法 - 简单教程&#xff0c;简单编程 (twle.cn) 代码解析 经过以上的分析我们可以理一下解题思路&#xff1a;接收参数反序列化之前先触发…...

RV1126 Linux 系统,接外设,时好时坏(一)应该从哪些方面排查问题

在 Linux 系统中接外设时,遇到“时好时坏”的问题,可能是由多种因素引起的。以下是一些排查问题的建议。 1. 硬件方面的排查 1.1 连接检查 物理连接: 确保外设与主板之间的连接良好,检查插头、插座及线缆是否牢固。引脚配置: 确认设备树中引脚的配置是否正确,尤其是引脚…...

Vue实现简单小案例

一、创建文件夹 二、引用vue.js <script src"../js/vue.js"></script> 三、准备一个容器 <div id"app"><h1>Hello,{{name}}</h1> </div> 四、创建实例 <script>new Vue({el:"#app", //el用于指…...

【MATLAB APP】建立独立桌面APP

背景&#xff1a;已有MATLAB APP的.mlapp文件&#xff0c;但客户提出需要可以直接使用的exe文件。 要求&#xff1a;点开即用&#xff0c;无需下载MATLAB。使用者无法修改APP的代码。 一、环境配置 APP创建者&#xff1a;安装MATLAB R2023a&#xff0c;配置Application Compile…...

Spring的优缺点?

Spring的优缺点 直接回答相关的Spring的特点&#xff1a; IOC AOP 事务 简化开发&#xff1a; 容易集成JDBCTemplateRestTemplate&#xff08;接口远程调用&#xff09;邮件发送相关异步消息请求支持 更加深入就讲源码了 优点&#xff1a; 方便解耦&#xff0c;简化开发…...

第一百八十三节 Java IO教程 - Java目录事件、Java异步I/O

Java IO教程 - Java目录事件 当文件系统中的对象被修改时&#xff0c;我们可以监听watch服务以获取警报。 java.nio.file包中的以下类和接口提供watch服务。 Watchable接口WatchService接口WatchKey接口WatchEvent接口WatchEvent.Kind接口StandardWatchEventKinds类 可监视对…...

【设计模式】(万字总结)深入理解Java中的创建型设计模式

1. 前言 在软件开发的世界里&#xff0c;设计模式是一种被广泛接受并应用的解决方案。它们不仅仅是代码的设计&#xff0c;更是对问题的思考和解决的方法论。在Java开发中&#xff0c;特别是在面向对象的编程中&#xff0c;设计模式尤为重要。创建型设计模式&#xff0c;作为设…...

【全面讲解下Docker in Docker的原理与实践】

🌈个人主页: 程序员不想敲代码啊 🏆CSDN优质创作者,CSDN实力新星,CSDN博客专家 👍点赞⭐评论⭐收藏 🤝希望本文对您有所裨益,如有不足之处,欢迎在评论区提出指正,让我们共同学习、交流进步! 👉目录 👉前言👉原理👉实践👉安全和最佳实践👉前言 🦛…...

Android Settings增加多击事件,增加开发者模式打开难度

软件平台&#xff1a;Android11 硬件平台&#xff1a;QCS6125 需求来源&#xff1a;用户通过系统异常崩溃&#xff0c;进入原生Settings页面&#xff0c;通过默认的多击版本号方式打开开发者模式&#xff0c;继而打开adb调试开关&#xff0c;安装三方apk。 对付这种需求本来有…...

【相机与图像】1. 相机模型的介绍:内参、外参、畸变参数

想着整理下相机模型&#xff08;内容上参考 slam十四讲&#xff09;、相机的内外参标定。方便自己的使用和回顾。 不过&#xff0c;内外参标定啥时候记录随缘 -_- 概述 【构建相机模型】 相机将三位世界中的坐标点&#xff08;单位为米&#xff09;映射到二维图像平面&#xff…...

Linux内核netlink机制 - 用户空间和内核空间数据传输

简介&#xff1a; Netlink socket 是一种Linux特有的socket&#xff0c;用于实现用户空间与内核空间通信的一种特殊的进程间通信方式(IPC) &#xff0c;也是网络应用程序与内核通信的最常用的接口。 Netlink 是一种在内核和用户应用间进行双向数据传输的非常好的方式&a…...

ES6从入门到精通:前言

ES6简介 ES6&#xff08;ECMAScript 2015&#xff09;是JavaScript语言的重大更新&#xff0c;引入了许多新特性&#xff0c;包括语法糖、新数据类型、模块化支持等&#xff0c;显著提升了开发效率和代码可维护性。 核心知识点概览 变量声明 let 和 const 取代 var&#xf…...

【入坑系列】TiDB 强制索引在不同库下不生效问题

文章目录 背景SQL 优化情况线上SQL运行情况分析怀疑1:执行计划绑定问题?尝试:SHOW WARNINGS 查看警告探索 TiDB 的 USE_INDEX 写法Hint 不生效问题排查解决参考背景 项目中使用 TiDB 数据库,并对 SQL 进行优化了,添加了强制索引。 UAT 环境已经生效,但 PROD 环境强制索…...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

【大模型RAG】Docker 一键部署 Milvus 完整攻略

本文概要 Milvus 2.5 Stand-alone 版可通过 Docker 在几分钟内完成安装&#xff1b;只需暴露 19530&#xff08;gRPC&#xff09;与 9091&#xff08;HTTP/WebUI&#xff09;两个端口&#xff0c;即可让本地电脑通过 PyMilvus 或浏览器访问远程 Linux 服务器上的 Milvus。下面…...

汽车生产虚拟实训中的技能提升与生产优化​

在制造业蓬勃发展的大背景下&#xff0c;虚拟教学实训宛如一颗璀璨的新星&#xff0c;正发挥着不可或缺且日益凸显的关键作用&#xff0c;源源不断地为企业的稳健前行与创新发展注入磅礴强大的动力。就以汽车制造企业这一极具代表性的行业主体为例&#xff0c;汽车生产线上各类…...

oracle与MySQL数据库之间数据同步的技术要点

Oracle与MySQL数据库之间的数据同步是一个涉及多个技术要点的复杂任务。由于Oracle和MySQL的架构差异&#xff0c;它们的数据同步要求既要保持数据的准确性和一致性&#xff0c;又要处理好性能问题。以下是一些主要的技术要点&#xff1a; 数据结构差异 数据类型差异&#xff…...

Mobile ALOHA全身模仿学习

一、题目 Mobile ALOHA&#xff1a;通过低成本全身远程操作学习双手移动操作 传统模仿学习&#xff08;Imitation Learning&#xff09;缺点&#xff1a;聚焦与桌面操作&#xff0c;缺乏通用任务所需的移动性和灵活性 本论文优点&#xff1a;&#xff08;1&#xff09;在ALOHA…...

算法岗面试经验分享-大模型篇

文章目录 A 基础语言模型A.1 TransformerA.2 Bert B 大语言模型结构B.1 GPTB.2 LLamaB.3 ChatGLMB.4 Qwen C 大语言模型微调C.1 Fine-tuningC.2 Adapter-tuningC.3 Prefix-tuningC.4 P-tuningC.5 LoRA A 基础语言模型 A.1 Transformer &#xff08;1&#xff09;资源 论文&a…...

推荐 github 项目:GeminiImageApp(图片生成方向,可以做一定的素材)

推荐 github 项目:GeminiImageApp(图片生成方向&#xff0c;可以做一定的素材) 这个项目能干嘛? 使用 gemini 2.0 的 api 和 google 其他的 api 来做衍生处理 简化和优化了文生图和图生图的行为(我的最主要) 并且有一些目标检测和切割(我用不到) 视频和 imagefx 因为没 a…...

【笔记】WSL 中 Rust 安装与测试完整记录

#工作记录 WSL 中 Rust 安装与测试完整记录 1. 运行环境 系统&#xff1a;Ubuntu 24.04 LTS (WSL2)架构&#xff1a;x86_64 (GNU/Linux)Rust 版本&#xff1a;rustc 1.87.0 (2025-05-09)Cargo 版本&#xff1a;cargo 1.87.0 (2025-05-06) 2. 安装 Rust 2.1 使用 Rust 官方安…...