MongoDB - 聚合阶段 $match、$sort、$limit

文章目录

    • 1. $match 聚合阶段
      • 1. 构造测试数据
      • 2. $match 示例
      • 3. $match 示例
    • 2. $sort 聚合阶段
      • 1. 排序一致性问题
      • 2. $sort 示例
    • 3. $limit 聚合阶段

1. $match 聚合阶段

$match 接受一个指定查询条件的文档。

$match 阶段语法:

{ $match: { <query> } }

$match 查询语法与读取操作查询语法相同,即 $match 不接受原始聚合表达式。要在 $match 中包含聚合表达式,请使用 $expr 查询表达式:

{ $match: { $expr: { <aggregation expression> } } }

尽可能早地将 $match 放在聚合管道中,由于 $match 限制了聚合管道中的文档总数,因此早期的 $match 操作会最大限度地减少管道中的处理量。

1. 构造测试数据

db.articles.drop()db.articles.insertMany([{"_id": ObjectId("512bc95fe835e68f199c8686"),"author": "dave","score": 80,"views": 100},{"_id": ObjectId("512bc962e835e68f199c8687"),"author": "dave","score": 85,"views": 521},{"_id": ObjectId("55f5a192d4bede9ac365b257"),"author": "ahn","score": 60,"views": 1000},{"_id": ObjectId("55f5a192d4bede9ac365b258"),"author": "li","score": 55,"views": 5000},{"_id": ObjectId("55f5a1d3d4bede9ac365b259"),"author": "annT","score": 60,"views": 50},{"_id": ObjectId("55f5a1d3d4bede9ac365b25a"),"author": "li","score": 94,"views": 999},{"_id": ObjectId("55f5a1d3d4bede9ac365b25b"),"author": "ty","score": 95,"views": 1000}
])

2. $match 示例

使用 $match 来执行简易等值匹配,$match 会选择 author 字段等于 dave 的文档,而聚合返回以下内容:

db.articles.aggregate([ { $match : { author : "dave" } } ]
);
// 1
{"_id": ObjectId("512bc95fe835e68f199c8686"),"author": "dave","score": 80,"views": 100
}// 2
{"_id": ObjectId("512bc962e835e68f199c8687"),"author": "dave","score": 85,"views": 521
}

SpringBoot 整合 MongoDB 实现:

@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void aggregateTest() {// $match阶段Criteria criteria = Criteria.where("author").is("dave");MatchOperation match = Aggregation.match(criteria);Aggregation aggregation = Aggregation.newAggregation(match);// 执行聚合管道操作AggregationResults<Article> results= mongoTemplate.aggregate(aggregation, Article.class, Article.class);List<Article> mappedResults = results.getMappedResults();// 打印结果mappedResults.forEach(System.out::println);//Article(id=512bc95fe835e68f199c8686, author=dave, score=80, views=100)//Article(id=512bc962e835e68f199c8687, author=dave, score=85, views=521)}
}

这里输出文档直接使用了Article.class,可以重新定义实体类接收输出文档的字段:

@Data
public class AggregationResult {@Idprivate String id;private String author;private int score;private int views;
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void aggregateTest() {// $match阶段Criteria criteria = Criteria.where("author").is("dave");MatchOperation match = Aggregation.match(criteria);Aggregation aggregation = Aggregation.newAggregation(match);// 执行聚合管道操作AggregationResults<AggregationResult> results= mongoTemplate.aggregate(aggregation, Article.class, AggregationResult.class);List<AggregationResult> mappedResults = results.getMappedResults();// 打印结果mappedResults.forEach(System.out::println);//AggregationResult(id=512bc95fe835e68f199c8686, author=dave, score=80, views=100)//AggregationResult(id=512bc962e835e68f199c8687, author=dave, score=85, views=521)}
}

3. $match 示例

使用 $match 管道操作符选择要处理的文档,然后将结果导入到 $group 管道操作符,以计算文档的数量:

db.articles.aggregate( [// 第一阶段{ $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },// 第二阶段{ $group: { _id: null, count: { $sum: 1 } } }
] );

第一阶段:

$match 阶段选择 score 大于 70 但小于 90views 大于或等于 1000 的文档。

第二阶段:

m a t c h 阶段筛选的文档通过管道传送到 ‘ match 阶段筛选的文档通过管道传送到 ` match阶段筛选的文档通过管道传送到group` 阶段进行计数。

// 1
{"_id": null,"count": 5
}

SpringBoot 整合 MongoDB 实现:

@Data
@Document(collection = "articles")
public class Article {@Idprivate String id;private String author;private int score;private int views;
}
@Data
public class AggregationResult {private String id;private Integer count;
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void aggregateTest() {// 第一阶段Criteria criteria = new Criteria();criteria.orOperator(Criteria.where("score").gt(70).lt(90), Criteria.where("views").gte(1000));MatchOperation match = Aggregation.match(criteria);// 第二阶段GroupOperation group = Aggregation.group().count().as("count");// 组合上面的2个阶段Aggregation aggregation = Aggregation.newAggregation(match,group);// 执行聚合管道操作AggregationResults<AggregationResult> results= mongoTemplate.aggregate(aggregation, Article.class, AggregationResult.class);List<AggregationResult> mappedResults = results.getMappedResults();// 打印结果mappedResults.forEach(System.out::println);// AggregationResult(id=null, count=5)}
}

2. $sort 聚合阶段

$sort 将所有输入文档进行排序,然后按照排序将其返回至管道。

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sort 接受排序依据的字段及相应排序顺序的文档。当 sort order=1时升序排序,sort order=-1 降序排序。

如果对多个字段进行排序,则按从左到右的顺序进行排序。例如,在上面的表单中,文档首先按 field1 排序。然后,具有相同 field1 值的文档将按 field2 进一步排序。

1. 排序一致性问题

MongoDB 不按特定顺序将文档存储在集合中。对包含重复值的字段进行排序时,可能会以任何顺序返回包含这些值的文档。如果需要一致的排序顺序,请在排序中至少纳入一个包含唯一值的字段。

db.restaurants.drop()db.restaurants.insertMany( [{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
] )

以下命令使用 $sort 阶段对 borough 字段进行排序:

db.restaurants.aggregate([{ $sort : { borough : 1 } }]
)

在此示例中,排序顺序可能不一致,因为 borough 字段包含 ManhattanBrooklyn 的重复值。文档按 borough 的字母顺序返回,但具有 borough 重复值的文档的顺序在多次执行同一排序中可能不相同。

要实现一致的排序,可以在排序中添加一个仅包含唯一值的字段。以下命令使用 $sort 阶段对 borough 字段和 _id 字段进行排序:

db.restaurants.aggregate([{ $sort : { borough : 1, _id: 1 } }]
)

由于 _id 字段始终保证包含唯一值,因此在同一排序的多次执行中返回的排序顺序将始终相同。

2. $sort 示例

db.articles.drop()db.articles.insertMany([{"_id": ObjectId("512bc95fe835e68f199c8686"),"author": "dave","score": 80,"views": 100},{"_id": ObjectId("512bc962e835e68f199c8687"),"author": "dave","score": 85,"views": 521},{"_id": ObjectId("55f5a192d4bede9ac365b257"),"author": "ahn","score": 60,"views": 1000},{"_id": ObjectId("55f5a192d4bede9ac365b258"),"author": "li","score": 55,"views": 5000},{"_id": ObjectId("55f5a1d3d4bede9ac365b259"),"author": "annT","score": 55,"views": 50},{"_id": ObjectId("55f5a1d3d4bede9ac365b25a"),"author": "li","score": 94,"views": 999},{"_id": ObjectId("55f5a1d3d4bede9ac365b25b"),"author": "ty","score": 95,"views": 1000}
])

对于要作为排序依据的一个或多个字段,可以将排序顺序设置为 1-1 以分别指定升序或降序。

db.articles.aggregate([{ $sort : { score : -1, views: 1 } }]
)
// 1
{"_id": ObjectId("55f5a1d3d4bede9ac365b25b"),"author": "ty","score": 95,"views": 1000
}// 2
{"_id": ObjectId("55f5a1d3d4bede9ac365b25a"),"author": "li","score": 94,"views": 999
}// 3
{"_id": ObjectId("512bc962e835e68f199c8687"),"author": "dave","score": 85,"views": 521
}// 4
{"_id": ObjectId("512bc95fe835e68f199c8686"),"author": "dave","score": 80,"views": 100
}// 5
{"_id": ObjectId("55f5a192d4bede9ac365b257"),"author": "ahn","score": 60,"views": 1000
}// 6
{"_id": ObjectId("55f5a1d3d4bede9ac365b259"),"author": "annT","score": 55,"views": 50
}// 7
{"_id": ObjectId("55f5a192d4bede9ac365b258"),"author": "li","score": 55,"views": 5000
}

SpringBoot 整合 MongoDB:

@Data
@Document(collection = "articles")
public class Article {@Idprivate String id;private String author;private int score;private int views;
}@Data
public class AggregationResult {@Idprivate String id;private String author;private int score;private int views;
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void aggregateTest() {// $sort阶段SortOperation sortOperation = Aggregation.sort(Sort.by(Sort.Direction.DESC, "score")).and(Sort.by(Sort.Direction.ASC, "views"));Aggregation aggregation = Aggregation.newAggregation(sortOperation);// 执行聚合查询AggregationResults<AggregationResult> results= mongoTemplate.aggregate(aggregation, Article.class, AggregationResult.class);List<AggregationResult> mappedResults = results.getMappedResults();// 打印结果mappedResults.forEach(System.out::println);//AggregationResult(id=55f5a1d3d4bede9ac365b25b, author=ty, score=95, views=1000)//AggregationResult(id=55f5a1d3d4bede9ac365b25a, author=li, score=94, views=999)//AggregationResult(id=512bc962e835e68f199c8687, author=dave, score=85, views=521)//AggregationResult(id=512bc95fe835e68f199c8686, author=dave, score=80, views=100)//AggregationResult(id=55f5a192d4bede9ac365b257, author=ahn, score=60, views=1000)//AggregationResult(id=55f5a1d3d4bede9ac365b259, author=annT, score=55, views=50)//AggregationResult(id=55f5a192d4bede9ac365b258, author=li, score=55, views=5000)}
}

3. $limit 聚合阶段

$limit 聚合阶段限制传递至管道。$limit 取一个正整数,用于指定传递的最大文档数量:

{ $limit: <positive 64-bit integer> }

如果将 $limit 阶段与以下任何一项一起使用:

  • $sort 聚合阶段
  • sort() 方法
  • sort 命令

在将结果传递到$limit阶段之前,请务必在排序中至少包含一个包含唯一值的字段。

db.articles.drop()db.articles.insertMany([{"_id": ObjectId("512bc95fe835e68f199c8686"),"author": "dave","score": 80,"views": 100},{"_id": ObjectId("512bc962e835e68f199c8687"),"author": "dave","score": 85,"views": 521},{"_id": ObjectId("55f5a192d4bede9ac365b257"),"author": "ahn","score": 60,"views": 1000},{"_id": ObjectId("55f5a192d4bede9ac365b258"),"author": "li","score": 55,"views": 5000},{"_id": ObjectId("55f5a1d3d4bede9ac365b259"),"author": "annT","score": 60,"views": 50},{"_id": ObjectId("55f5a1d3d4bede9ac365b25a"),"author": "li","score": 94,"views": 999},{"_id": ObjectId("55f5a1d3d4bede9ac365b25b"),"author": "ty","score": 95,"views": 1000}
])
db.articles.aggregate([{ $limit : 5 }
]);
// 1
{"_id": ObjectId("512bc95fe835e68f199c8686"),"author": "dave","score": 80,"views": 100
}// 2
{"_id": ObjectId("512bc962e835e68f199c8687"),"author": "dave","score": 85,"views": 521
}// 3
{"_id": ObjectId("55f5a192d4bede9ac365b257"),"author": "ahn","score": 60,"views": 1000
}// 4
{"_id": ObjectId("55f5a192d4bede9ac365b258"),"author": "li","score": 55,"views": 5000
}// 5
{"_id": ObjectId("55f5a1d3d4bede9ac365b259"),"author": "annT","score": 55,"views": 50
}

SpringBoot 整合 MongoDB:

@Data
@Document(collection = "articles")
public class Article {@Idprivate String id;private String author;private int score;private int views;
}@Data
public class AggregationResult {@Idprivate String id;private String author;private int score;private int views;
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void aggregateTest() {// $sort阶段LimitOperation limitOperation = Aggregation.limit(5);Aggregation aggregation = Aggregation.newAggregation(limitOperation);// 执行聚合查询AggregationResults<AggregationResult> results= mongoTemplate.aggregate(aggregation, Article.class, AggregationResult.class);List<AggregationResult> mappedResults = results.getMappedResults();// 打印结果mappedResults.forEach(System.out::println);//AggregationResult(id=512bc95fe835e68f199c8686, author=dave, score=80, views=100)//AggregationResult(id=512bc962e835e68f199c8687, author=dave, score=85, views=521)//AggregationResult(id=55f5a192d4bede9ac365b257, author=ahn, score=60, views=1000)//AggregationResult(id=55f5a192d4bede9ac365b258, author=li, score=55, views=5000)//AggregationResult(id=55f5a1d3d4bede9ac365b259, author=annT, score=55, views=50)}
}

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

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

相关文章

图形学和音视频开发哪个更有钱景,更值得入行?

图形学有几个细分的方向&#xff0c;在开始前刚好我有一些资料&#xff0c;是我根据网友给的问题精心整理了一份「音视频开发的资料从专业入门到高级教程」&#xff0c; 点个关注在评论区回复“888”之后私信回复“888”&#xff0c;全部无偿共享给大家&#xff01;&#xff0…

PHP教程002:PHP变量介绍

文章目录 一、PHP程序1、PHP标记2、PHP代码3、语句结束符;4、注释 二、PHP变量2.1 声明变量2.2 赋值运算符3、变量命名规则 一、PHP程序 PHP文件的默认扩展名是".php"PHP文件可以包含html、css、js 序号组成描述1<?php ... ?>PHP标记2PHP代码函数、数组、流…

昇思25天学习打卡营第20天|munger85

GAN图像生成 生成对抗网络中是为了让我们生成的东西向期望的那样&#xff0c;就是为了让生成的东西很像&#xff0c;真的&#xff0c;例如用它来画画。就是描述整个网络的逻辑和目的&#xff0c;它有两部分组成&#xff0c;一个是生成器&#xff0c;一个是辨别器。他希望的是辨…

C++ 沙漏图案(Hour-glass Pattern)

给定正整数 n&#xff0c;以沙漏形式打印数字模式。示例&#xff1a; 输入&#xff1a;rows_no 7 输出&#xff1a; 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6…

工商业储能配套能量管理系统在储能中扮演重要角色

工商业储能能量管理系统&#xff08;EMS&#xff09;在工商业储能系统中扮演着至关重要的角色。以下是对该系统的详细解析&#xff1a; 一、系统定义与功能 定义&#xff1a; 工商业储能能量管理系统是一种专门设计用于监控和管理工商业储能电站的系统。它通过对储能设备的实…

SQL注入之数据库和系统库2024.7.28

SQL注入之数据库概述 数据库就是一个存储数据的仓库&#xff0c;数据库是以一定方式存储在一起&#xff0c;能与多个用户共享&#xff0c;具有尽可能小的冗余&#xff0c;与应用程序彼此独立的数据集合。 常见的关系型数据库有MySQL&#xff0c;Orcale&#xff0c;PostgreSQL…

如何在 VitePress 中自定义logo,打造精美首页 #home-hero-image

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐&#xff1a;「storm…

React 和 Vue _使用区别

目录 一、框架介绍 1.Vue 2.React 二、框架结构 1.创建应用 2.框架结构 三、使用区别 1.单页面组成 2.样式 3.显示响应式数据 4.响应式html标签属性 5.控制元素显隐 6.条件渲染 7.渲染列表 react和vue是目前前端比较流行的两大框架&#xff0c;前端程序员应该将两…

go-kratos 学习笔记(8) redis的使用

redis的在项目中的使用是很常见的&#xff0c;前面有了mysql的使用redis的也差不多&#xff1b;也是属于在data层的操作&#xff0c;所以需要新建一个 NewRedisCmd方法 在internal/data/data.go中新增NewRedisCmd 方法&#xff0c;注入到ProviderSet package dataimport (&quo…

Windows linux环境下操作redis数据库

在Windows系统安装redis下载一步一步即可安装。上设置Redis密码的过程与Linux系统类似,但需注意几个关键步骤以确保正确配置,这篇文章主要给大家介绍环境下查看、添加、修改redis数据库的密码两种方式,需要的朋友可以参考下 windows开始之前先启动redis服务&#xff0c;然后再…

正则采集器之五——商品匹配规则

需求设计 实现分析 系统通过访问URL得到html代码&#xff0c;通过正则表达式匹配html&#xff0c;通过反向引用来得到商品的标题、图片、价格、原价、id&#xff0c;这部分逻辑在java中实现。 匹配商品的正则做成可视化编辑&#xff0c;因为不同网站的结构不同&#xff0c;同…

论文阅读:A Survey on Evaluation of Large Language Models-鲁棒性相关内容

A Survey on Evaluation of Large Language Models 只取了鲁棒性相关的内容 LLMs&#xff1a;《A Survey on Evaluation of Large Language Models大型语言模型评估综述》理解智能本质(具备推理能力)、AI评估的重要性(识别当前算法的局限性设 对抗鲁棒性是衡量大型语言模型&…

C++参悟:accumulate 累加器

accumulate 累加器 一、概述二、快速代码版1. 简单的容器求和2. 带自定义求和器去求和3. 重载 运算符号 一、概述 accumulate 有两个参数版本如下&#xff1a; template< class InputIt, class T > T accumulate( InputIt first, InputIt last, T init );template<…

ComfyUI 、ComfyUI-Manager、ComfyUI-Translation语言包、Insightface、Crystools资源监测器安装

简单介绍ComfyUI、ComfyUI-Manager、ComfyUI-Translation语言包、Insightface、Crystools资源监测器安装&#xff0c;并通过ComfyUI-Manager安装缺失的节点。 1、ComfyUI安装 打开https://github.com/comfyanonymous/ComfyUI&#xff0c;找到Installing中 Direct link to do…

phpenv安装redis扩展

1、下载dll文件 https://pecl.php.net/package/redis 我的是php8.1, 安装最新版的 DLL文件 &#xff12;、将dll文件放到php安装目录的ext目录下 3、在php.ini中增加配置后重启服务 [Redis] extension php_redis.dll

VMware安装(有的时候启动就蓝屏建议换VM版本)

当你开始使用虚拟化技术来管理和运行多个操作系统时&#xff0c;VMware 是一个强大且广泛使用的选择。本篇博客将指导你如何安装 VMware Workstation Pro&#xff0c;这是一个功能强大的虚拟机软件&#xff0c;适用于个人和专业用户。 一、下载 VMware Workstation Pro 访问官网…

JavaScript青少年简明教程:函数及其相关知识(上)

JavaScript青少年简明教程&#xff1a;函数及其相关知识&#xff08;上&#xff09; 在JavaScript中&#xff0c;函数是一段可以重复使用的代码块&#xff0c;它执行特定的任务并可能返回结果。 内置函数&#xff08;Built-in Functions&#xff09; 内置函数是编程语言中预先…

ES里面常用的查询语句有哪些?

【编程电子书大全】链接: https://pan.baidu.com/s/1yhPJ9LmS_z5TdgIgxs9NvQ?pwdyyds > 提取码: yyds Elasticsearch&#xff08;ES&#xff09;中常用的查询语句包括以下几类&#xff1a; 1. Match 查询 用于全文搜索&#xff0c;匹配指定字段中的文本。 GET /index_na…

PLC网关:开启工业4.0时代的智能工厂之路

PLC即可编程逻辑控制器&#xff0c;是工业自动化领域的核心设备&#xff0c;广泛应用于各个工业领域。从PLC问世至今&#xff0c;一直表现出强大的生命力和高速增长态势&#xff0c;2020年全球PLC市场的销售量已经达到了百亿RMB级别。 随着行业智能化、数字化推广&#xff0c;…

【Vulnhub系列】Vulnhub_Seattle_003靶场渗透(原创)

【Vulnhub系列靶场】Vulnhub_Seattle_003靶场渗透 原文转载已经过授权 原文链接&#xff1a;Lusen的小窝 - 学无止尽&#xff0c;不进则退 (lusensec.github.io) 一、环境准备 1、从百度网盘下载对应靶机的.ova镜像 2、在VM中选择【打开】该.ova 3、选择存储路径&#xff0…