1、数据准备
1.1、springboot导包
点击查看代码-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-mongodb</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.83</version>
- </dependency>
复制代码 1.2、配置文件yml
点击查看代码- spring:
- data:
- mongodb:
- # 有账号密码
- uri: mongodb://账户名:密码@IP:端口/数据库
- # 无账号密码
- # uri: mongodb://IP:端口/数据库
复制代码 1.3、实体类
点击查看代码- package com.cc.mdb.entity;
- import lombok.Data;
- import org.springframework.data.annotation.Id;
- import org.springframework.data.mongodb.core.mapping.Document;
- import org.springframework.data.mongodb.core.mapping.Field;
- import java.time.LocalDateTime;
- /**
- * @Document("User") 存入的时候不取对象名,默认用User当做表名
- */
- @Data
- @Document("User")
- public class User {
- @Id
- private String id;
- /**
- * 使用name当做字段key
- */
- @Field("name")
- private String name;
- /**
- * 使用age1当做字段key
- */
- @Field("age1")
- private Integer age;
- /**
- * 使用email当做字段key
- */
- @Field("email")
- private String email;
- /**
- * 使用createDate当做字段key
- */
- @Field("createDate")
- private LocalDateTime createDate = LocalDateTime.now();
- }
复制代码 2、基础CRUD
点击查看代码- package com.cc.mdb.test;
- import com.alibaba.fastjson.JSONObject;
- import com.cc.mdb.BaseTest;
- import com.cc.mdb.entity.User;
- import com.mongodb.client.result.UpdateResult;
- import org.junit.Test;
- import org.springframework.data.domain.PageRequest;
- import org.springframework.data.domain.Pageable;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.data.mongodb.core.query.Update;
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- import java.util.regex.Pattern;
- /** CRUD
- * 查询使用:Query
- * 博客:https://blog.csdn.net/weixin_44185213/article/details/125293170?spm=1001.2014.3001.5502
- * @author CC
- * @since 2023/3/30 0030
- */
- @SpringBootTest
- @RunWith(SpringRunner.class)
- public class TestMongoQuery{
- @Resource
- private MongoTemplate mongoTemplate;
- //写入简单数据 —— 根据对象存数据
- @Test
- public void test01()throws Exception{
- List<User> vos = new ArrayList<>();
- for (int i = 10; i < 20; i++) {
- User user = new User();
- String aa = i + "" + i + "" + i + "";
- user.setId(aa);
- user.setName("cscs"+aa);
- user.setAge(123);
- user.setEmail("11@qq.com");
- vos.add(user);
- }
- Collection<User> user2 = mongoTemplate.insert(vos, "User2");
- System.out.println(user2);
- }
- //写入简单数据 —— 根据json存数据(JSONObject(Fastjson))
- @Test
- public void test02()throws Exception{
- List<JSONObject> vos = new ArrayList<>();
- for (int i = 1; i < 20; i++) {
- JSONObject result = new JSONObject();
- String aa = i + "" + i + "" + i + "";
- result.put("id",aa);
- result.put("name","cscs"+aa);
- result.put("age",123);
- result.put("email","11@qq.com");
- vos.add(result);
- }
- Collection<JSONObject> user3 = mongoTemplate.insert(vos, "User3");
- System.out.println(user3);
- }
- //写入复杂数据 —— 有子文档(json数据中有下级)
- @Test
- public void test013()throws Exception{
- List<JSONObject> vos = new ArrayList<>();
- for (int i = 1; i < 20; i++) {
- JSONObject result = new JSONObject();
- String aa = i + "" + i + "" + i + "";
- result.put("id",aa);
- result.put("name","cscs"+aa);
- result.put("age",123);
- result.put("email","11@qq.com");
- List<JSONObject> jss = new ArrayList<>();
- for (int j = 0; j < 2; j++) {
- JSONObject js = new JSONObject();
- js.put("sId",j);
- js.put("sName","学校" + aa);
- js.put("sNo","学校编号" + aa);
- js.put("sTab",1);
- List<JSONObject> whats = new ArrayList<>();
- if (i == 1){
- for (int k = 0; k < 2; k++) {
- JSONObject kk = new JSONObject();
- kk.put("kId",k);
- kk.put("kName","k"+k);
- whats.add(kk);
- }
- }
- js.put("sWhat",whats);
- jss.add(js);
- }
- result.put("school",jss);
- vos.add(result);
- }
- Collection<JSONObject> user3 = mongoTemplate.insert(vos, "User4");
- System.out.println(user3);
- }
- //查找全部
- @Test
- public void test03()throws Exception{
- List<User> users = mongoTemplate.findAll(User.class);
- System.out.println(users);
- }
- /** 根据json里面的字段查询
- * 查询 school.sWhat.kId 的数据
- */
- @Test
- public void test07()throws Exception{
- //查询的新增方法:test013
- Criteria cr = new Criteria();
- // cr.and("id").is("111");
- // cr.and("school.sId").is(0);
- cr.and("school.sWhat.kId").is(0);
- Query query = new Query();
- query.addCriteria(cr);
- // 执行查询并获取结果
- List<JSONObject> jsonObjects = mongoTemplate.find(query, JSONObject.class, "User4");
- System.out.println(jsonObjects);
- }
- //**高级查询:使用Query
- @Test
- public void test04()throws Exception{
- String search = "cscs";
- int page = 1;
- int size = 20;
- Query query = new Query();
- //一、where
- //1模糊
- String format = String.format("^.*%s.*$", search);
- Pattern pattern = Pattern.compile(format, Pattern.CASE_INSENSITIVE);
- Criteria criteria = Criteria.where("name").regex(pattern);
- //模糊查询方式2(推荐)
- // Criteria.where("name").regex(String.format(".*%s.*","查询的值"));
- //2等于(这里比较特殊,value:数字的必须传入数字的、字符串必须传入字符串的)
- criteria.and("age").is(123);
- query.addCriteria(criteria);
- //二、排序。按id升序
- Sort sort = Sort.by(Sort.Direction.ASC, "_id");
- query.with(sort);
- //二、总条数(是所有条件都弄了之后)
- long totalCount = mongoTemplate.count(query, JSONObject.class, "User3");
- //三、分页(必须在where和查询总条数之后)
- //方式1
- // query.skip((page - 1) * size).limit(size);
- //方式2(推荐)
- Pageable pageable = PageRequest.of(page - 1, size);
- query.with(pageable);
- //查询。由于查询出来的是key-value的形式,可以使用JSONObject(FastJson)来接收参数。如果有对象(User),可以直接使用对象来接收
- List<JSONObject> users = mongoTemplate.find(query, JSONObject.class, "User3");
- System.out.println("总条数:" + totalCount);
- System.out.println(users);
- }
- //修改 - 根据表名+id 修改其中一个json中的某些值
- @Test
- public void test05() {
- JSONObject user2 = mongoTemplate.findById("6433c76df108474b788cc4ce", JSONObject.class, "User3");
- Object id = user2.get("_id");
- Query query = new Query(Criteria.where("_id").is(id));
- Update update = new Update();
- update.set("name", "修改后的名字2");
- update.set("age", "321");
- // update.set("email", "");
- //方式1:upsert方法更新与查询条件匹配的第一个文档,如果没有文档与查询条件匹配,则插入一个新文档。
- // UpdateResult result = mongoTemplate.upsert(query, update, "User3");
- // long count = result.getModifiedCount();
- // System.out.println(count);
- //方式2:update方法更新与查询条件匹配的第一个文档
- UpdateResult user3 = mongoTemplate.updateFirst(query, update, "User3");
- //修改计数
- long modifiedCount = user3.getModifiedCount();
- System.out.println(modifiedCount);
- //匹配计数
- long matchedCount = user3.getMatchedCount();
- System.out.println(matchedCount);
- //方式3:updateMulti方法更新与查询条件匹配的所有文档。
- // UpdateResult user31 = mongoTemplate.updateMulti(query, update, "User3");
- }
- //删除 - 根据数据id删除
- @Test
- public void test06() {
- //1删除文档中的某一条数据
- // Query query = new Query(Criteria.where("_id").is("6433c76df108474b788cc4cf"));
- // DeleteResult result = mongoTemplate.remove(query, "User3");
- // long count = result.getDeletedCount();
- // System.out.println(count);
- //2删除整个文档中的数据 —— 相当于drop清空表中的数据
- // DeleteResult user4 = mongoTemplate.remove(new Query(), "User4");
- // long deletedCount = user4.getDeletedCount();
- // System.out.println(deletedCount);
- //3删除文档 —— 相当于删除表
- mongoTemplate.dropCollection("User4");
- }
- }
复制代码 3、聚合查询
3.1、聚合查询关键字
- * $project 指定返回字段
- * $lookup 多表关联
- * $unwind 数组拆分
- * $match 筛选条件
- * $sort 排序
- * $limit 分页
- * $skip 跳过
- * $group 根据id(可自定义)分组
- * $sum 分组后求和
- * $first 分组后取第一条
- * $last 分组后取最后一条
- * $addToSet 分组后添加到list
- * $cond 可以做 if-else
复制代码 3.2、聚合查询
点击查看代码- package com.cc.mdb.test;
- import com.alibaba.fastjson.JSONObject;
- import com.cc.mdb.BaseTest;
- import org.junit.Test;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.aggregation.*;
- import org.springframework.data.mongodb.core.query.Criteria;
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- /**
- * 聚合查询
- * $project 指定返回字段
- * $lookup 多表关联
- * $unwind 数组拆分
- * $match 筛选条件
- * $sort 排序
- * $limit 分页
- * $skip 跳过
- * $group 根据id(可自定义)分组
- * $sum 分组后求和
- * $first 分组后取第一条
- * $last 分组后取最后一条
- * $addToSet 分组后添加到list
- * $cond 可以做 if-else
- * @author CC
- * @since 2023/4/20 0020
- */
- public class TestMongoAgg extends BaseTest {
- @Resource
- private MongoTemplate mongoTemplate;
- private static final String COLLECTION_NAME = "USER";
- /** 分组
- */
- @Test
- public void test00()throws Exception{
- Aggregation groupAgg = Aggregation.newAggregation(
- Aggregation.group("age") // 分组条件
- .first("age").as("age_R") // 获取分组后查询到的该字段的第一个值
- // .first("school.sId").as("sId_R")
- .sum("age").as("sum_age_R") // 按分组对该字段求和
- .avg("age").as("avg_age_R") // 按分组求该字段平均值
- .sum("id").as("sum_id_R") // 按age分组后求id的和
- .min("id").as("min_id_R") // 按age分组后求id的最小值
- .max("id").as("max_id_R") // 按age分组后求id的最大值
- );
- AggregationResults<JSONObject> results = mongoTemplate.aggregate(groupAgg, COLLECTION_NAME, JSONObject.class);
- List<JSONObject> res = results.getMappedResults();
- System.out.println(res);
- }
- /** 聚合查询:数组拆分 + 指定返回字段 + 排序 + 分页
- */
- @Test
- public void testAgg01()throws Exception{
- // 1. 配置聚合查询
- // 1.1. 将school字段分解成数组
- UnwindOperation unwind = Aggregation.unwind("school");
- // 1.2. 获取school.sId的属性中大于2的对象
- MatchOperation match = Aggregation.match(Criteria.where("school.sId").gt(2));
- // 1.3. 显示的字段
- ProjectionOperation project = Aggregation.project("_id", "school.sId",
- "school.sName", "name", "id", "age", "email");
- // 1.4. 查询所有
- Aggregation aggregation = Aggregation.newAggregation(
- unwind,
- match,
- project
- );
- // 1.5. 查询数量:把数量封装在totalCount这个值中
- Aggregation countAgg = Aggregation.newAggregation(
- unwind,
- match,
- Aggregation.count().as("totalCount")
- );
- // 1.6. 排序+分页
- Aggregation sortAndSkipLimitAgg = Aggregation.newAggregation(
- unwind,
- match,
- project,
- // 1.6.1. 排序:先按照sId升序,再按照id降序
- Aggregation.sort(Sort.Direction.ASC,"sId")
- .and(Sort.Direction.DESC,"id"),
- // 1.6.2. 分页
- Aggregation.skip(0L),
- Aggregation.limit(2L)
- );
- // 2. 查询
- // 2.1. 查询全部
- AggregationResults<JSONObject> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, JSONObject.class);
- // 2.1.1. 获取映射结果
- List<JSONObject> allResult = results.getMappedResults();
- allResult.forEach(System.out::println);
- // 2.2. 查询数量
- AggregationResults<JSONObject> resultCount = mongoTemplate.aggregate(countAgg, COLLECTION_NAME, JSONObject.class);
- JSONObject jsonObject = resultCount.getUniqueMappedResult();
- System.out.println(jsonObject);
- Object totalCount = jsonObject.get("totalCount");
- System.out.println("总数:" + totalCount);
- // 2.3. 排序+分页查询
- AggregationResults<JSONObject> sortSkip = mongoTemplate.aggregate(sortAndSkipLimitAgg, COLLECTION_NAME, JSONObject.class);
- List<JSONObject> mappedResults = sortSkip.getMappedResults();
- System.out.println(mappedResults);
- //获取原始结果
- // Document rawResults = results.getRawResults();
- //获取唯一映射结果(只获取一个值)
- // JSONObject uniqueMappedResult = results.getUniqueMappedResult();
- //获取服务器使用情况
- // String serverUsed = results.getServerUsed();
- //循环:和mappedResults循环一样的
- // results.forEach(result -> {
- // System.out.println(result);
- // });
- }
- //添加聚合查询的数据
- @Test
- public void testAgg02() throws Exception {
- //写入复杂数据 —— 有子文档(json数据中有下级)
- List<JSONObject> vos = new ArrayList<>();
- for (int i = 1; i < 20; i++) {
- JSONObject result = new JSONObject();
- String aa = i + "" + i + "" + i + "";
- result.put("id", aa);
- result.put("name", "cscs" + aa);
- int age = 123;
- if (i >= 10){
- age = 345;
- }
- result.put("age", age);
- result.put("email", "11@qq.com");
- List<JSONObject> jss = new ArrayList<>();
- if (i < 6){
- for (int j = 1; j < 3; j++) {
- JSONObject js = new JSONObject();
- js.put("sId", j * i);
- js.put("sName", "学校" + aa);
- js.put("sNo", "学校编号" + aa);
- js.put("sTab", j * i);
- jss.add(js);
- }
- }
- result.put("school", jss);
- vos.add(result);
- }
- Collection<JSONObject> user3 = mongoTemplate.insert(vos, COLLECTION_NAME);
- System.out.println(user3);
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |