当前位置: 首页 > 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);}}

http://www.lryc.cn/news/338944.html

相关文章:

  • labview中FP.isFrontmost不生效?
  • Vela-OS: 记录一个class层,处理MSC协议的bug
  • 跨框架探索:React Redux 和 Vuex 对比分析快速掌握React Redux
  • 第十五届蓝桥杯省赛C/C++大学B组真题及赛后总结
  • 【Qt踩坑】ARM 编译Qt5.14.2源码-QtWebEngine
  • SQL语法 case when语句用法讲解
  • Project Euler_Problem 193_Few Repeated Digits_欧拉筛+容斥公式
  • 排序算法-基数排序
  • ChatGPT在线网页版
  • 5.SpringSpringBoot八股
  • 0基础刷图论最短路 3(从ATcoder 0分到1800分)
  • k8s+docker一键安装过程
  • Python3+Appium+Android SDK+真机+实现app自动化测试-基于Red Hat7.9版本搭建环境及运行python脚本。
  • 深入理解MD5算法:原理、应用与安全
  • 架构师系列-搜索引擎ElasticSearch(三)- Java API
  • Ubuntu下配置Android NDK环境
  • 使用 vue3-sfc-loader 加载远程Vue文件, 在运行时动态加载 .vue 文件。无需 Node.js 环境,无需 (webpack) 构建步骤
  • stm32移植嵌入式数据库FlashDB
  • Ubuntu 安装Java、Git、maven、Jenkins等持续集成环境
  • 文件批量重命名并批量修改文件扩展名,支持随机大小写字母命名并修改扩展名字母
  • 【管理咨询宝藏70】MBB大型城投集团内外部环境分析报告
  • 服务器挖矿病毒解决ponscan,定时任务解决
  • 【鸿蒙开发】第二十一章 Media媒体服务(二)--- 音频播放和录制
  • 网络安全从入门到精通(特别篇I):Windows安全事件应急响应之Windows应急响应基础必备技能
  • 基于SpringBoot+Mybatis框架的私人影院预约系统(附源码,包含数据库文件)
  • 【SERVERLESS】AWS Lambda上实操
  • IDEA2023 开发环境配置
  • YOLOV5 + 双目相机实现三维测距(新版本)
  • 【计算机网络】(一)计算机网络概述
  • 前端npm常用命令总结