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

MongoDB的使用

一、Spring Boot集成MongoDB

1 引用依赖包

  <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>

2 配置文件配置mongodb资料

# MongoDB连接信息
spring.data.mongodb.host = 192.168.23.27
spring.data.mongodb.port = 27017
spring.data.mongodb.database = mall
#自动创建索引
spring.data.mongodb.auto-index-creation = true

3 准备对象Person        

@Document(collection = "person") // 指定集合名称,就是类似mysql的表,如果不指定就以类名称作为集合名称
@Data
public class Person {@Id // 文档id, 很重要,类似mysql表的主键private Long id;private String name;private Integer age;/*** 创建一个10秒之后文档自动删除的索引 结合 spring.data.mongodb.auto-index-creation = true 一起使用创建一个10秒之后文档自动删除, 类似 redis ttl
注意:这个字段必须是date类型或者是一个包含date类型值的数组字段,一般我们使用date类型;*/@Indexed(expireAfterSeconds=10)private LocalDateTime createTime;
}

二、Spring Boot操作MongoDB 

1 新增文档

单个插入

    @Autowiredprivate MongoTemplate mongoTemplate;/*** 插入文档*/@Testvoid insert() {Person person =new Person();person.setId(20530712L);person.setName("张三");person.setAge(26);mongoTemplate.insert(person);}/*** 自定义集合,插入文档*/@Testpublic void insertCustomCollection() throws Exception {Person person =new Person();person.setId(20530712L);person.setName("张三");person.setAge(26);person.setCreateTime(LocalDateTimeUtil.now());mongoTemplate.insert(person, "custom_person");}/*** 批量插入文档*/@Testpublic void insertBatch() throws Exception {List<Person> personList = new ArrayList<>();for (int i = 1; i < 5; i++) {Person person =new Person();person.setId((long) i);person.setName("张三"+i);person.setAge(26);person.setCreateTime(LocalDateTimeUtil.now());personList.add(person);}//mongoTemplate.insert(personList, "custom_person");mongoTemplate.insertAll(personList);}/*** 存储文档,如果没有插入,否则更新* 在存储文档的时候会通过主键 ID 进行判断,如果存在就更新,否则就插入*/@Testpublic void save() throws Exception {Person person =new Person();person.setId(1L);person.setName("张三33");person.setAge(26);person.setCreateTime(LocalDateTimeUtil.now());mongoTemplate.save(person);}

2 修改文档

@Autowiredprivate MongoTemplate mongoTemplate;/*** 更新文档,匹配查询到的文档数据中的第一条数据* @throws Exception*/@Testpublic void update1() throws Exception {//更新条件Query query= new Query(Criteria.where("id").is(2));//更新值Update update= new Update().set("name", person.getName()).set("age", 32);//更新查询满足条件的文档数据(第一条)UpdateResult result =mongoTemplate.updateFirst(query, update, Person.class);System.out.println("更新条数:" + result.getMatchedCount());}/*** 更新文档,匹配查询到的文档数据中的所有数据*/@Testpublic void updateMany() throws Exception {//更新年龄大于等于32的人Query query= new Query(Criteria.where("age").gte(18));//更新姓名为 “我成人了”Update update= new Update().set("name", "我成人了");//更新查询满足条件的文档数据(全部)UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);System.out.println("更新条数:" + result.getMatchedCount());}

3 删除文档

   @Autowiredprivate MongoTemplate mongoTemplate;/*** 删除符合条件的所有文档*/@Testpublic void remove() throws Exception {//删除年龄小于18的所有人Query query = new Query(Criteria.where("age").lt(18));DeleteResult result = mongoTemplate.remove(query, Person.class);System.out.println("删除条数:" + result.getDeletedCount());}/*** 删除符合条件的单个文档,并返回删除的文档*/@Testpublic void findAndRemove() throws Exception {Query query = new Query(Criteria.where("id").is(1L));Person result = mongoTemplate.findAndRemove(query, Person.class);System.out.println("删除的文档数据:" + result);}/*** 删除符合条件的所有文档,并返回删除的文档*/@Testpublic void findAllAndRemove() throws Exception {// 使用 in 删除 符合条件的多条文档,并返回Query query = new Query(Criteria.where("id").in(1,2,3));List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);System.out.println("删除的文档数据:" + result.toString());}

3 查询文档        

1.原生查询        

db.getCollection("my_person").find({ name: /^张/ ,name: /大$/}) db.getCollection("my_person").find({ name: /^张/,age:{$lte:12}})

2.Java实现

@Autowiredprivate MongoTemplate mongoTemplate;/*** 查询集合中的全部文档数据*/@Testpublic void findAll()  {List<Person> result = mongoTemplate.findAll(Person.class);System.out.println("查询结果:" + result.toString());}/*** 查询集合中指定的ID文档数据*/@Testpublic void findById() {long id = 2L;Person result = mongoTemplate.findById(id, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据条件查询集合中符合条件的文档,返回第一条数据*/@Testpublic void findOne() {Query query = new Query(Criteria.where("name").is("张三3"));Person result = mongoTemplate.findOne(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据条件查询所有符合条件的文档*/@Testpublic void findByCondition() {Query query = new Query(Criteria.where("age").gt(18));List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据【AND】关联多个查询条件,查询集合中所有符合条件的文档数据*/@Testpublic void findByAndCondition() {// 创建条件Criteria name = Criteria.where("name").is("张三");Criteria age = Criteria.where("age").is(18);// 创建条件对象,将上面条件进行 AND 关联Criteria criteria = new Criteria().andOperator(name, age);// 创建查询对象,然后将条件对象添加到其中Query query = new Query(criteria);List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据【OR】关联多个查询条件,查询集合中的文档数据*/@Testpublic void findByOrCondition() {// 创建条件Criteria criteriaUserName = Criteria.where("name").is("张三");Criteria criteriaPassWord = Criteria.where("age").is(22);// 创建条件对象,将上面条件进行 OR 关联Criteria criteria = new Criteria().orOperator(criteriaUserName, criteriaPassWord);// 创建查询对象,然后将条件对象添加到其中Query query = new Query(criteria);List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据【IN】关联多个查询条件,查询集合中的文档数据*/@Testpublic void findByInCondition() {// 设置查询条件参数List<Long> ids = Arrays.asList(10L, 11L, 12L);// 创建条件Criteria criteria = Criteria.where("id").in(ids);// 创建查询对象,然后将条件对象添加到其中Query query = new Query(criteria);List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据【逻辑运算符】查询集合中的文档数据*/@Testpublic void findByOperator() {// 设置查询条件参数int min = 20;int max = 35;Criteria criteria = Criteria.where("age").gt(min).lte(max);// 创建查询对象,然后将条件对象添加到其中Query query = new Query(criteria);List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据【正则表达式】查询集合中的文档数据*/@Testpublic void findByRegex() {// 设置查询条件参数String regex = "^张";Criteria criteria = Criteria.where("name").regex(regex);// 创建查询对象,然后将条件对象添加到其中Query query = new Query(criteria);List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据条件查询集合中符合条件的文档,获取其文档列表并排序*/@Testpublic void findByConditionAndSort() {Query query = new Query(Criteria.where("name").is("张三")).with(Sort.by("age"));List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目*/@Testpublic void findByConditionAndSortLimit() {String userName = "张三";//从第5行开始,查询3条数据返回Query query = new Query(Criteria.where("name").is("张三")).with(Sort.by("createTime")).limit(3).skip(5);List<Person> result = mongoTemplate.find(query, Person.class);System.out.println("查询结果:" + result.toString());}/*** 统计集合中符合【查询条件】的文档【数量】*/@Testpublic void countNumber() {// 设置查询条件参数String regex = "^张*";Criteria criteria = Criteria.where("name").regex(regex);// 创建查询对象,然后将条件对象添加到其中Query query = new Query(criteria);long count = mongoTemplate.count(query, Person.class);System.out.println("统计结果:" + count);}

4 创建索引

@Autowiredprivate MongoTemplate mongoTemplate;/*** 创建升序索引*/@Testpublic void createAscendingIndex() {// 设置字段名称String field = "age";// 创建索引mongoTemplate.getCollection("person").createIndex(Indexes.descending(field));}/*** 根据索引名称移除索引*/@Testpublic void removeIndex() {// 设置字段名称String field = "age_1";// 删除索引mongoTemplate.getCollection("person").dropIndex(field);}/*** 查询集合中所有的索引*/@Testpublic void getIndexAll() {// 获取集合中所有列表ListIndexesIterable<Document> indexList =   mongoTemplate.getCollection("person").listIndexes();// 获取集合中全部索引信息for (Document document : indexList) {System.out.println("索引列表:" + document);}}

相关文章:

MongoDB的使用

一、Spring Boot集成MongoDB 1 引用依赖包 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency> 2 配置文件配置mongodb资料 # MongoDB连接信息 spring.…...

labview中FP.isFrontmost不生效?

主GUI界面中调用子GUI程序FP.isFrontmost不生效&#xff1f; 如果主GUI程序使用“floating”,子GUI程序使用default动作&#xff0c;则子GUI无法打开到最前。子GUI程序只能使用“模态”才能置顶。 主GUI程序&#xff1a; 子GUI程序&#xff1a; 改正的方法很简单&#xff0c…...

Vela-OS: 记录一个class层,处理MSC协议的bug

一、关于USC-MSC类设备驱动层,处理SCSI指令的代码逻辑问题 1. 源文件 \nuttx\drivers\usbdev\usbmsc_scsi.c 2. 问题描述 对于INQUIRY指令,长度一般是6个字节,cdblen字段嵌入在CBW数据包中,如下: 命令阶段的CBW数据包: 55 53 42 43 60 2a c0 8b 24 00 00 00 0x80 0x…...

跨框架探索:React Redux 和 Vuex 对比分析快速掌握React Redux

React Redux 和 Vuex 都是前端状态管理库&#xff0c;分别用于 React 和 Vue.js 框架。 它们都提供了一套规范的状态管理机制&#xff0c;帮助开发者更好地组织和管理应用状态。下面是它们的一些异同点&#xff1a; 相同点&#xff1a; 中心化状态管理&#xff1a;两者都提…...

第十五届蓝桥杯省赛C/C++大学B组真题及赛后总结

目录 个人总结 C/C 组真题 握手问题 小球反弹 好数 R 格式 宝石组合 数字接龙 爬山 拔河 ​编辑 再总结及后续规划 个人总结 第一次参加蓝桥杯&#xff0c;大二&#xff0c;以前都在在学技术&#xff0c;没有系统的学过算法。所以&#xff0c;还是花了挺多时间去备…...

【Qt踩坑】ARM 编译Qt5.14.2源码-QtWebEngine

1.下载源码 下载网站&#xff1a;Index of /new_archive/qt/5.14/5.14.2/single 2.QWebEngine相关依赖 sudo apt-get install flex libicu-dev libxslt-dev sudo apt-get install libssl-dev libxcursor-dev libxcomposite-dev libxdamage-dev libxrandr-dev sudo apt-get …...

SQL语法 case when语句用法讲解

CASE WHEN解释 &#xff1a; SQL中的CASE WHEN语句是一种条件表达式&#xff0c;它允许你根据不同的情况返回不同的值。CASE WHEN通常用于SELECT语句中&#xff0c;用于创建新的列&#xff0c;该列的值取决于其他列的值。CASE WHEN可以用于任何可以使用表达式的地方。 大致概…...

Project Euler_Problem 193_Few Repeated Digits_欧拉筛+容斥公式

解题思路&#xff1a;暴力搜索 代码&#xff1a; void solve() {ll i, j,k,x,y,z,p,q,u,v,l,l1;N 999966663333, NN 1024;//N 1000;double a, b, c,d;M.NT.get_prime_Euler(1000000);l M.NT.pcnt;for (i 1; i < l; i) {u M.NT.prime[i];v M.NT.prime[i 1];x u * …...

排序算法-基数排序

基数排序是一种非比较排序算法&#xff0c;它将待排序的数字按照位数进行排序。基数排序的思想是先按照个位数进行排序&#xff0c;然后按照十位数进行排序&#xff0c;接着按照百位数进行排序&#xff0c;以此类推&#xff0c;直到最高位排序完成。 基数排序的步骤如下&#x…...

ChatGPT在线网页版

ChatGPT镜像 今天在知乎看到一个问题&#xff1a;“平民不参与内测的话没有账号还有机会使用ChatGPT吗&#xff1f;” 从去年GPT大火到现在&#xff0c;关于GPT的消息铺天盖地&#xff0c;真要有心想要去用&#xff0c;途径很多&#xff0c;别的不说&#xff0c;国内GPT的镜像…...

5.SpringSpringBoot八股

Spring,Spring MVC,Spring Boot 之间什么关系? Spring就是整个Spring框架的整体&#xff0c;包含AOP、JDBC、Spring MVC等等模块 SpringBoot是Spring的精简版&#xff0c;它在Spring的基础上添加了自动装配、内置tomcat服务器等功能&#xff0c;使得代码量更少&#xff0c;同…...

0基础刷图论最短路 3(从ATcoder 0分到1800分)

AT最短路刷题3&#xff08;本文难度rated 1200~ 1400&#xff09; 题目来源&#xff1a;Atcoder 题目收集&#xff1a; https://atcoder-tags.herokuapp.com/tags/Graph/Shortest-Path &#xff08;里面按tag分类好了Atcoder的所有题目&#xff0c;类似cf&#xff09; &#x…...

k8s+docker一键安装过程

环境: k8s 1.20 docker 20.10 centos7.9 #docker安装 yum install -y epel-release yum install -y yum-utils yum-config-manager --add-repo https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo yum install -y docker-ce-20.10.6 docker-ce-cli-2…...

Python3+Appium+Android SDK+真机+实现app自动化测试-基于Red Hat7.9版本搭建环境及运行python脚本。

1、总体概述? 收费有收费的服务,那就是细致。Red Hat9.0自动化环境也有,需要的说一声。 1、实现在Red Ha/t Enterprise Linux7.9环境中搭建部署app自动化测试环境,提供详细步骤。 2、版本说明:jdk8/17+nodejs16/18/19/20/21+android sdk29+python3.9.18/3.11.1+appium1…...

深入理解MD5算法:原理、应用与安全

title: 深入理解MD5算法&#xff1a;原理、应用与安全 date: 2024/4/11 20:55:57 updated: 2024/4/11 20:55:57 tags: MD5算法数据安全哈希函数摘要算法安全漏洞SHA算法密码学 第一章&#xff1a;引言 导言 在当今数字化时代&#xff0c;数据安全和完整性变得至关重要。消息…...

架构师系列-搜索引擎ElasticSearch(三)- Java API

SpringBoot整合ES 搭建SpringBoot工程&#xff0c;引入ElasticSearch相关坐标 <!--引入es的坐标--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><versi…...

Ubuntu下配置Android NDK环境

Android-NDK的下载 下载Android-NDK wget -c http://dl.google.com/android/ndk/android-ndk-r10e-linux-x86_64.bin 执行bin文件&#xff08;即解压&#xff09; ./android-ndk-r10c-linux-x86_64.bin Android-NDK的配置 要想使用Android-NDK&#xff0c;还需要进行环境变量…...

使用 vue3-sfc-loader 加载远程Vue文件, 在运行时动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤

加载远程Vue文件 vue3-sfc-loader vue3-sfc-loader &#xff0c;它是Vue3/Vue2 单文件组件加载器。 在运行时从 html/js 动态加载 .vue 文件。无需 Node.js 环境&#xff0c;无需 (webpack) 构建步骤。 主要特征 支持 Vue 3 和 Vue 2&#xff08;参见dist/&#xff09;仅需…...

stm32移植嵌入式数据库FlashDB

本次实验的程序链接stm32f103FlashDB嵌入式数据库程序资源-CSDN文库 一、介绍 FlashDB 是一款超轻量级的嵌入式数据库&#xff0c;专注于提供嵌入式产品的数据存储方案。与传统的基于文件系统的数据库不同&#xff0c;FlashDB 结合了 Flash 的特性&#xff0c;具有较强的性能…...

Ubuntu 安装Java、Git、maven、Jenkins等持续集成环境

Ubuntu 持续集成 安装OpenJdk 查看所有可安装的 JDK 版本 apt list OpenJDK\*使用 apt 安装 JDK&#xff08;以 11为例&#xff09;,最好是用11&#xff0c;java8对应的jenkins会有兼容问题。 sudo apt install openjdk-11-jdk openjdk-11-jre安装成功后&#xff0c;可以使用以…...

深入剖析AI大模型:大模型时代的 Prompt 工程全解析

今天聊的内容&#xff0c;我认为是AI开发里面非常重要的内容。它在AI开发里无处不在&#xff0c;当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗"&#xff0c;或者让翻译模型 "将这段合同翻译成商务日语" 时&#xff0c;输入的这句话就是 Prompt。…...

第一篇:Agent2Agent (A2A) 协议——协作式人工智能的黎明

AI 领域的快速发展正在催生一个新时代&#xff0c;智能代理&#xff08;agents&#xff09;不再是孤立的个体&#xff0c;而是能够像一个数字团队一样协作。然而&#xff0c;当前 AI 生态系统的碎片化阻碍了这一愿景的实现&#xff0c;导致了“AI 巴别塔问题”——不同代理之间…...

C++.OpenGL (10/64)基础光照(Basic Lighting)

基础光照(Basic Lighting) 冯氏光照模型(Phong Lighting Model) #mermaid-svg-GLdskXwWINxNGHso {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-GLdskXwWINxNGHso .error-icon{fill:#552222;}#mermaid-svg-GLd…...

工业自动化时代的精准装配革新:迁移科技3D视觉系统如何重塑机器人定位装配

AI3D视觉的工业赋能者 迁移科技成立于2017年&#xff0c;作为行业领先的3D工业相机及视觉系统供应商&#xff0c;累计完成数亿元融资。其核心技术覆盖硬件设计、算法优化及软件集成&#xff0c;通过稳定、易用、高回报的AI3D视觉系统&#xff0c;为汽车、新能源、金属制造等行…...

【论文阅读28】-CNN-BiLSTM-Attention-(2024)

本文把滑坡位移序列拆开、筛优质因子&#xff0c;再用 CNN-BiLSTM-Attention 来动态预测每个子序列&#xff0c;最后重构出总位移&#xff0c;预测效果超越传统模型。 文章目录 1 引言2 方法2.1 位移时间序列加性模型2.2 变分模态分解 (VMD) 具体步骤2.3.1 样本熵&#xff08;S…...

【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)

1.获取 authorizationCode&#xff1a; 2.利用 authorizationCode 获取 accessToken&#xff1a;文档中心 3.获取手机&#xff1a;文档中心 4.获取昵称头像&#xff1a;文档中心 首先创建 request 若要获取手机号&#xff0c;scope必填 phone&#xff0c;permissions 必填 …...

【碎碎念】宝可梦 Mesh GO : 基于MESH网络的口袋妖怪 宝可梦GO游戏自组网系统

目录 游戏说明《宝可梦 Mesh GO》 —— 局域宝可梦探索Pokmon GO 类游戏核心理念应用场景Mesh 特性 宝可梦玩法融合设计游戏构想要素1. 地图探索&#xff08;基于物理空间 广播范围&#xff09;2. 野生宝可梦生成与广播3. 对战系统4. 道具与通信5. 延伸玩法 安全性设计 技术选…...

安卓基础(aar)

重新设置java21的环境&#xff0c;临时设置 $env:JAVA_HOME "D:\Android Studio\jbr" 查看当前环境变量 JAVA_HOME 的值 echo $env:JAVA_HOME 构建ARR文件 ./gradlew :private-lib:assembleRelease 目录是这样的&#xff1a; MyApp/ ├── app/ …...

IP如何挑?2025年海外专线IP如何购买?

你花了时间和预算买了IP&#xff0c;结果IP质量不佳&#xff0c;项目效率低下不说&#xff0c;还可能带来莫名的网络问题&#xff0c;是不是太闹心了&#xff1f;尤其是在面对海外专线IP时&#xff0c;到底怎么才能买到适合自己的呢&#xff1f;所以&#xff0c;挑IP绝对是个技…...

BLEU评分:机器翻译质量评估的黄金标准

BLEU评分&#xff1a;机器翻译质量评估的黄金标准 1. 引言 在自然语言处理(NLP)领域&#xff0c;衡量一个机器翻译模型的性能至关重要。BLEU (Bilingual Evaluation Understudy) 作为一种自动化评估指标&#xff0c;自2002年由IBM的Kishore Papineni等人提出以来&#xff0c;…...