MongoDB的使用

embedded/2024/10/18 0:27:54/

一、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.ppmy.cn/embedded/6967.html

相关文章

存储竞赛,角逐未来

随着人工智能&#xff08;AI&#xff09;和大数据驱动的海量数据需求&#xff0c;对存储技术的要求也在不断提高。在此背景下&#xff0c;各大存储芯片巨头之间的技术竞赛日益激烈。 在NAND闪存领域&#xff0c;企业关注的重点在于层数的突破。近日&#xff0c;《韩国经济日报》…

Meta通过开源Llama 3 LLM提高了标准

Meta 推出了 Llama 3,这是其最先进的开源大型语言模型(LLM)的下一代产品。这家科技巨头声称,Llama 3 在现实场景中建立了新的性能基准,超越了之前行业领先的模型,如 GPT-3.5。 Meta 在一篇博文中宣布了这一发布,并表示:"通过 Llama 3,我们致力于打造与当今最好的专有模型…

上位机图像处理和嵌入式模块部署(树莓派4b和驱动的编写)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 树莓派4b上面还支持驱动代码的编写&#xff0c;这是我没有想到的。这里驱动&#xff0c;更多的是一种框架的编写&#xff0c;不一定是编写真正的驱…

c++二分排序(向右

描述 给出有 n 个元素的由小到大的序列&#xff0c;请你编程找出某元素最后一次出现的位置。 (n<10^6 输入描述 第一行&#xff1a;一个整数&#xff0c;表示由小到大序列元素个数&#xff1b;下面 n 行&#xff0c;每行一个整数&#xff1b; 最后一行 一个整数 x&#x…

iOS知识点---Runloop

iOS 中的 Runloop 机制是一种事件驱动模型&#xff0c;用于管理和调度线程上的事件&#xff0c;确保线程在有工作要做时保持活跃&#xff0c;无事可做时进入休眠状态以节省系统资源。以下是 Runloop 机制的关键组成部分及其工作原理&#xff1a; 关键组成部分与原理&#xff1…

基于springboot实现智能物流管理系统设计项目【项目源码+论文说明】

基于springboot实现智能物流管理系统演示 摘要 随着信息技术在管理上越来越深入而广泛的应用&#xff0c;管理信息系统的实施在技术上已逐步成熟。本文介绍了智能物流管理系统的开发全过程。通过分析智能物流管理系统管理的不足&#xff0c;创建了一个计算机管理智能物流管理系…

ES6 全详解 let 、 const 、解构赋值、剩余运算符、函数默认参数、扩展运算符、箭头函数、新增方法,promise、Set、class等等

目录 ES6概念ECMAScript6简介ECMAScript 和 JavaScript 的关系ES6 与 ECMAScript 2015 的关系 1、let 、 const 、var 区别2、变量解构赋值1、数组解构赋值2、对象解构赋值3、字符串的解构赋值 3、展开剩余运算符1、**展开运算符(...)**2、**剩余运算符(...)** 4、函数的拓展函…

【PyTorch】1-基础知识(张量、导数、CUDA)

PyTorch&#xff1a;1-基础知识 注&#xff1a;所有资料来源且归属于thorough-pytorch(https://datawhalechina.github.io/thorough-pytorch/)&#xff0c;下文仅为学习记录 1.1&#xff1a;张量 神经网络核心包&#xff1a;autograd&#xff08;自动微分&#xff09; 张量…