• MongoDB基础学习(五)之在Springboot项目使用MongoTemplate进行操作


     springboot简单操作MongoDB——-增删改查 

    1.引入依赖

    1. <!--MongoDB starter-->
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-data-mongodb</artifactId>
    5. </dependency>

    2.在配置文件中进行配置

    application.properties配置数据源

    1. spring.data.mongodb.host=xxx.xxx.xxx.xxx
    2. spring.data.mongodb.port=xxxxxx
    3. spring.data.mongodb.database=xxxxx
    4. spring.data.mongodb.username=xxxx
    5. spring.data.mongodb.password=xxxxx

    1.建立实体类。

    1. /**
    2. * @Date: 2018/8/28 21:22
    3. * @Description:
    4. */
    5. @Data
    6. @Document("Entry") // 声明文档为Entry
    7. public class Entry {
    8. private String id;
    9. private String name;
    10. private Integer age;
    11. private String remark;
    12. public String getId() {
    13. return id;
    14. }
    15. public void setId(String id) {
    16. this.id = id;
    17. }
    18. public String getName() {
    19. return name;
    20. }
    21. public void setName(String name) {
    22. this.name = name;
    23. }
    24. public Integer getAge() {
    25. return age;
    26. }
    27. public void setAge(Integer age) {
    28. this.age = age;
    29. }
    30. public String getRemark() {
    31. return remark;
    32. }
    33. public void setRemark(String remark) {
    34. this.remark = remark;
    35. }
    36. }

    springBoot2.3 使用MongoRepository整合mongoDb

    创建Dao接口

    继承MongoRepository接口,第一个泛型是document文档对象,第二个参数是id的类型,一般直接设置为String类型就行了,让mongo自动生成id

    1. @Repository
    2. public interface EntryDao extends MongoRepository<Entry, String> {
    3. }

    Service接口

    1. /**
    2. * 使用mongoRepository接口,基本能够完成增删改查操作,包括批量插入,批量修改,模糊查询,删除所有,删除满足条件的;
    3. * 查询满足任一条件的数据,查询满足所有条件的数据;分页查询;查询结果排序
    4. */
    5. public interface EntryService {
    6. /**
    7. * 新增,插入(不能插入相同id的数据)
    8. * @param po
    9. * @return
    10. */
    11. Entry insertEntry(Entry po);
    12. /**
    13. * 修改,如果id存在则修改,如果id不存在则新增
    14. * @param po
    15. * @return
    16. */
    17. Entry updateEntry(Entry po);
    18. /**
    19. * 插入多条
    20. * @param EntryList
    21. * @return
    22. */
    23. List<Entry> insertManyEntry(List<Entry> EntryList);
    24. /**
    25. * 查询一条(即使是有多条数据也只是返回第一条)
    26. * @param po
    27. * @return
    28. */
    29. EntryfindEntry(Entry po);
    30. /**
    31. * 查询多条数据
    32. * @param po
    33. * @return
    34. */
    35. List<Entry> findEntryList(Entry po);
    36. /**
    37. * 查询结果排序
    38. * @param po
    39. * @return
    40. */
    41. List<Entry> findEntryListSort(Entry po);
    42. /**
    43. * 查询满足任意一个条件的多条数据
    44. * @param po
    45. * @return
    46. */
    47. List<Entry> findEntryListAny(Entry po);
    48. /**
    49. * 模糊查询
    50. * @param po
    51. * @return
    52. */
    53. List<Entry> findEntryListLike(Entry po);
    54. /**
    55. * 模糊查询2
    56. * @param po
    57. * @return
    58. */
    59. List<Entry> findEntryListLike2(Entry po);
    60. /**
    61. * 分页查询
    62. * @param po
    63. * @return
    64. */
    65. Page<Entry> findEntryListByPage(Entry po, int page, int size);
    66. /**
    67. * 删除所有
    68. */
    69. void deleteAll();
    70. /**
    71. * 根据id删除
    72. * @param id
    73. */
    74. void deleteById(String id);
    75. /**
    76. * 判断是否存在
    77. * @param po
    78. * @return
    79. */
    80. Boolean exists(Entry po);
    81. }

    ServiceImpl 实现类

    1. @Service
    2. public class EntryServiceImpl implements EntryService {
    3. @Autowired
    4. private EntryDao entrydao;
    5. @Override
    6. public Entry insertEntry(Entry po) {
    7. // 新增
    8. return entrydao.insert(po);
    9. }
    10. @Override
    11. public Entry updateEntry(Entry po) {
    12. // 如果不存在则新增,存在则修改
    13. return entrydao.save(po);
    14. }
    15. @Override
    16. public List<Entry> insertManyEntry(List<Entry> EntryList) {
    17. return entrydao.insert(EntryList);
    18. }
    19. @Override
    20. public Entry findEntry(Entry po) {
    21. Example<Entry> of = Example.of(po);
    22. Optional<Entry> one = entrydao.findOne(of);
    23. return one.get();
    24. }
    25. @Override
    26. public List<Entry> findEntryList(Entry po) {
    27. // Example.of(po) 默认就是 ExampleMatcher.matching() 匹配模式
    28. return entrydao.findAll(Example.of(po));
    29. }
    30. @Override
    31. public List<Entry> findEntryListSort(Entry po) {
    32. // 构造排序器,按title字段降序排列,如果有多个字段则,分别按多个字段的进行降序
    33. Sort sort = Sort.by(Sort.Direction.DESC,"title");
    34. return entrydao.findAll(Example.of(po), sort);
    35. }
    36. @Override
    37. public List<Entry> findEntryListAny(Entry po) {
    38. // 设置为或模式,默认是且模式,或表示查询条件中的任意一个条件满足都返回。是指不同的查询字段,而不是同一个字段的不同值
    39. ExampleMatcher matcher = ExampleMatcher.matchingAny();
    40. Example<Entry> example = Example.of(po, matcher);
    41. return entrydao.findAll(example);
    42. }
    43. @Override
    44. public List<Entry> findEntryListLike(Entry po) {
    45. // 设置不同字段的查询方式:模糊查询
    46. // 必须是ExampleMatcher.matching().withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())的方式写,
    47. // 不能分开写成ExampleMatcher matcher = ExampleMatcher.matching(); matcher.withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
    48. // 因为源码中就说了This instance is immutable and unaffected by this method call
    49. // title字段 以包含方式查询,即sql中的 like '%关键词%'
    50. // description字段以查询结尾的方式查询,即sql中的 like '%关键词'
    51. // 测试1"title"
    52. ExampleMatcher matcher = ExampleMatcher.matching()
    53. .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
    54. .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());
    55. // 测试2: 不写title时,默认应该是精确查询的
    56. /*ExampleMatcher matcher = ExampleMatcher.matching()
    57. .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());*/
    58. Example<Entry> example = Example.of(po, matcher);
    59. return entrydao.findAll(example);
    60. }
    61. public List<Entry> findEntryListLike2(Entry po) {
    62. // 改变默认字符串匹配方式:直接把精确查询改为模糊查询
    63. // 必须是ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);的方式写,
    64. // 不能分开写成ExampleMatcher matcher = ExampleMatcher.matching(); matcher.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
    65. ExampleMatcher matcher = ExampleMatcher.matching()
    66. .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
    67. Example<Entry> example = Example.of(po, matcher);
    68. return entrydao.findAll(example);
    69. }
    70. @Override
    71. public Page<Entry> findEntryListByPage(Entry po, int page, int size) {
    72. // 改为模糊查询
    73. ExampleMatcher matcher = ExampleMatcher.matching()
    74. .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
    75. .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());
    76. // 测试2: 不写title时,默认应该是精确查询的
    77. /*ExampleMatcher matcher = ExampleMatcher.matching()
    78. .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());*/
    79. Example<Entry> example = Example.of(po, matcher);
    80. // 构造分页对象,带排序规则
    81. // Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "title");
    82. // 不带排序规则
    83. Pageable pageable = PageRequest.of(page, size);
    84. // 分页查询
    85. return entrydao.findAll(example, pageable);
    86. }
    87. @Override
    88. public void deleteAll() {
    89. entrydao.deleteAll();
    90. }
    91. @Override
    92. public void deleteById(String id) {
    93. entrydao.deleteById(id);
    94. }
    95. @Override
    96. public Boolean exists(Entry po) {
    97. return entrydao.exists(Example.of(po));
    98. }
    99. }

    测试
    日志使用lombok, 测试工具使用SpringBootTest

    1. @Slf4j
    2. @SpringBootTest
    3. public class EntryTest {
    4. @Autowired
    5. private EntryService entryService;
    6. @Test
    7. public void testInsertEntry() {
    8. Entry po = new Entry();
    9. // 有没有这个setId都可以,如果不设置则由mongodb自动生成一个id
    10. // po.setId("1");
    11. po.setTitle("今日大事件2");
    12. po.setDescription("今日大事件的描述2");
    13. Entry Entry = entryService.insertEntry(po);
    14. log.info("【新增话术】Entry:{}", Entry);
    15. }
    16. @Test
    17. public void testUpdateEntry() {
    18. Entry po = new Entry();
    19. po.setTitle("今日大事件3");
    20. Entry Entry = entryService.findEntry(po);
    21. Entry.setDescription("今日大事件3修改了呀2");
    22. EntryService.updateEntry(Entry);
    23. log.info("【修改话术】Entry:{}", Entry);
    24. }
    25. @Test
    26. public void testInsertManyEntry() {
    27. List<Entry> list = new ArrayList<>();
    28. for (int i = 0; i < 20; i++) {
    29. Entry po = new Entry();
    30. po.setTitle("今日热榜" + i);
    31. po.setDescription("今日热榜描述A" + i);
    32. list.add(po);
    33. }
    34. List<Entry> Entryes = entryService.insertManyEntry(list);
    35. log.info("【新增话术】Entry:{}", Entryes);
    36. }
    37. @Test
    38. public void testFindEntry() {
    39. Entry po = new Entry();
    40. po.setTitle("今日大事件2");
    41. Entry Entry = entryService.findEntry(po);
    42. log.info("【查询话术】Entry:{}", Entry);
    43. }
    44. @Test
    45. public void testFindEntryList() {
    46. Entry po = new Entry();
    47. po.setTitle("今日大事件2");
    48. List<Entry> EntryList = entryService.findEntryList(po);
    49. log.info("【查询话术】Entry:{}", EntryList);
    50. }
    51. @Test
    52. public void testFindEntryListByPage() {
    53. Entry po = new Entry();
    54. po.setTitle("今日热榜");
    55. Page<Entry> EntryListByPage = entryService.findEntryListByPage(po, 0, 10);
    56. int totalPages = EntryListByPage.getTotalPages();
    57. List<Entry> content = EntryListByPage.getContent();
    58. int number = EntryListByPage.getSize();
    59. int numberOfElements = EntryListByPage.getNumberOfElements();
    60. log.info("【分页查询话术】totalPage:{} number:{} , numberOfElements:{}, Entry:{}, ", totalPages, number,numberOfElements, content);
    61. }
    62. @Test
    63. public void testFindEntryListSort() {
    64. Entry po = new Entry();
    65. // po.setTitle("今日大事件2");
    66. List<Entry> EntryList = entryService.findEntryListSort(po);
    67. log.info("【话术查询结果排序】Entry:{}", EntryList);
    68. }
    69. @Test
    70. public void testFindEntryListAny() {
    71. Entry po = new Entry();
    72. po.setTitle("今日大事件2");
    73. po.setDescription("今日大事件的描述3");
    74. List<Entry> EntryList = entryService.findEntryListAny(po);
    75. log.info("【话术查询或】Entry:{}", EntryList);
    76. }
    77. @Test
    78. public void testFindEntryListLike() {
    79. Entry po = new Entry();
    80. po.setTitle("大事件3");
    81. // po.setDescription("3修改了呀2");
    82. // po.setTitle("今日大事件3");
    83. List<Entry> EntryList = entryService.findEntryListLike(po);
    84. log.info("【话术模糊查询】Entry:{}", EntryList);
    85. }
    86. @Test
    87. public void testFindEntryListLike2() {
    88. Entry po = new Entry();
    89. po.setTitle("大");
    90. po.setDescription("3");
    91. // po.setTitle("今日大事件3");
    92. List<Entry> EntryList = entryService.findEntryListLike2(po);
    93. log.info("【话术模糊查询】Entry:{}", EntryList);
    94. }
    95. @Test
    96. public void testDeleteAll() {
    97. EntryService.deleteAll();
    98. }
    99. @Test
    100. public void testDeleteById() {
    101. Entry po = new Entry();
    102. po.setTitle("今日大事件2");
    103. Entry Entry = entryService.findEntry(po);
    104. EntryService.deleteById(Entry.getId());
    105. log.info("【删除】Entry:{}", Entry);
    106. }
    107. @Test
    108. public void testExists() {
    109. Entry po = new Entry();
    110. po.setTitle("今日大事件3");
    111. Boolean exist = entryService.exists(po);
    112. log.info("【判断是否存在】:{}", exist);
    113. }
    114. }

    使用MongoTemplate进行简单的增删改查

    1. import org.junit.Test;
    2. import org.junit.runner.RunWith;
    3. import org.springframework.boot.test.context.SpringBootTest;
    4. import org.springframework.data.mongodb.core.MongoTemplate;
    5. import org.springframework.data.mongodb.core.query.Criteria;
    6. import org.springframework.data.mongodb.core.query.Query;
    7. import org.springframework.data.mongodb.core.query.Update;
    8. import org.springframework.test.context.junit4.SpringRunner;
    9. import java.util.List;
    10. /**
    11. * @Date: 2018/8/28 21:30
    12. * @Description:
    13. */
    14. @RunWith(SpringRunner.class)
    15. @SpringBootTest
    16. public class EntryTest {
    17. /**
    18. * 直接注入mongoTemplate即可使用
    19. * */
    20. private MongoTemplate mongoTemplate;
    21. //
    22. @Test
    23. public void add(Entry entry){
    24. entry.setId("1");
    25. entry.setName("张三");
    26. entry.setAge(15);
    27. entry.setRemark("喜欢打球、喜欢喝茶");
    28. //存储操作
    29. mongoTemplate.save(entry);
    30. //指定集合名
    31. mongoTemplate.save(entry,"人员表");
    32. }
    33. //删除
    34. @Test
    35. public void delete(String id){
    36. mongoTemplate.remove("1");
    37. mongoTemplate.remove("1","人员表");
    38. Query query = new Query();
    39. //拼装删除数据
    40. query.addCriteria(Criteria.where("id").is("1"));
    41. mongoTemplate.remove(query,"人员表");
    42. mongoTemplate.remove(query,Entry.class);
    43. }
    44. //
    45. @Test
    46. public void edit(Entry entry){
    47. Query query = new Query(Criteria.where("id").is(entry.getId()));
    48. //拼装修改数据
    49. Update update = new Update();
    50. update.set("name","李四");
    51. update.set("remark","喜欢画画");
    52. mongoTemplate.updateFirst(query, update, Entry.class);
    53. }
    54. //简单查
    55. @Test
    56. public void query(String id){
    57. //单条
    58. Query query = new Query(Criteria.where("id").is(id));//可累加条件
    59. Entry entrY = mongoTemplate.findOne(query,Entry.class);
    60. //多条
    61. Query query2 = new Query(Criteria.where("remark").regex("喜欢"));//可累加条件
    62. List<Entry> entries = mongoTemplate.find(query, Entry.class);
    63. }
    64. //查询所有
    65. @Test
    66. public void findAll(){
    67. List<Entry> entries = mongoTemplate.find(Entry.class);
    68. }
    69. //根据id查询
    70. @Test
    71. public void findById(Integer id){
    72. Query query=new Query(Criteria.where("_id").is(id));//可累加条件
    73. Entry student = mongoTemplate.findOne(query, Entry.class);
    74. }
    75. }

    分页查询——此处我写了两个工具类

    1. import org.springframework.data.domain.Sort;
    2. import java.io.Serializable;
    3. /**
    4. * @Auther:
    5. * @Date: 2018/8/22 08:48
    6. * @Description:
    7. * @Version: 1.0
    8. */
    9. public class MongoDBPageModel implements Serializable {
    10. /**
    11. * @Fields: serialVersionUID
    12. * @Todo: TODO
    13. */
    14. private static final long serialVersionUID = 1L;
    15. // 当前页
    16. private Integer pagenumber = 1;
    17. // 当前页面条数
    18. private Integer pagesize = 10;
    19. // 排序条件
    20. private Sort sort;
    21. public Integer getPagenumber() {
    22. return pagenumber;
    23. }
    24. public void setPagenumber(Integer pagenumber) {
    25. this.pagenumber = pagenumber;
    26. }
    27. public Integer getPagesize() {
    28. return pagesize;
    29. }
    30. public void setPagesize(Integer pagesize) {
    31. this.pagesize = pagesize;
    32. }
    33. public Sort getSort() {
    34. return sort;
    35. }
    36. public void setSort(Sort sort) {
    37. this.sort = sort;
    38. }
    39. }
    1. import java.io.Serializable;
    2. import org.springframework.data.domain.Pageable;
    3. import org.springframework.data.domain.Sort;
    4. /**
    5. * @Auther:
    6. * @Date: 2018/8/22 10:19
    7. * @Description:
    8. * @Version: 1.0
    9. */
    10. public class SpringbootMongoDBPageable implements Serializable,Pageable{
    11. /**
    12. * @Fields: serialVersionUID
    13. * @Todo: TODO
    14. */
    15. private static final long serialVersionUID = 1L;
    16. MongoDBPageModel page;
    17. public MongoDBPageModel getPage() {
    18. return page;
    19. }
    20. public void setPage(MongoDBPageModel page) {
    21. this.page = page;
    22. }
    23. @Override
    24. public Pageable first() {
    25. // TODO Auto-generated method stub
    26. return null;
    27. }
    28. @Override
    29. public int getOffset() {
    30. // TODO Auto-generated method stub
    31. return (page.getPagenumber() - 1) * page.getPagesize();
    32. }
    33. @Override
    34. public int getPageNumber() {
    35. // TODO Auto-generated method stub
    36. return page.getPagenumber();
    37. }
    38. @Override
    39. public int getPageSize() {
    40. // TODO Auto-generated method stub
    41. return page.getPagesize();
    42. }
    43. @Override
    44. public boolean hasPrevious() {
    45. // TODO Auto-generated method stub
    46. return false;
    47. }
    48. @Override
    49. public Pageable next() {
    50. // TODO Auto-generated method stub
    51. return null;
    52. }
    53. @Override
    54. public Pageable previousOrFirst() {
    55. // TODO Auto-generated method stub
    56. return null;
    57. }
    58. @Override
    59. public Sort getSort() {
    60. // TODO Auto-generated method stub
    61. return page.getSort();
    62. }
    63. }

    分页查询+分页聚合查询(多表多条件关联分页查询+结果集解析)——-依然测试类

    1. /**
    2. * @Date: 2018/8/28 21:30
    3. * @Description:
    4. */
    5. @RunWith(SpringRunner.class)
    6. @SpringBootTest
    7. public class EntryTest {
    8. /**
    9. * 直接注入mongoTemplate即可使用
    10. * */
    11. private MongoTemplate mongoTemplate;
    12. //分页查询
    13. @Test
    14. public void PageQuery(){
    15. //利用工具类拼装分页信息
    16. SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
    17. MongoDBPageModel pm=new MongoDBPageModel();
    18. pm.setPagesize(3);
    19. pm.setPagenumber(1);
    20. List<Order> orders = new ArrayList<>(); //排序信息
    21. orders.add(new Order(Direction.DESC, "age"));
    22. Sort sort = new Sort(orders);
    23. pm.setSort(sort);
    24. pageable.setPage(pm);
    25. //拼装查询信息
    26. Query query = new Query();
    27. Criteria criteria = new Criteria();
    28. query.addCriteria(criteria.where("age").gte(6).lte(18));//检索6-18岁的
    29. query.addCriteria(criteria.where("name").regex("文"));//模糊查询名字
    30. Long count = mongoTemplate.count(query, OrdersData.class);//查询总记录数
    31. List<Entry> list = mongoTemplate.find(query.with(pageable), Entry.class);
    32. }
    33. //分页聚合查询(多表多条件关联分页查询)
    34. @Test
    35. public void PageQuery2(){
    36. //mongodb中有两个表,一个是人物表 一个是宠物表,一个人可以有多个宠物
    37. //人物表字段为 String id, Integer age,String remark;
    38. //宠物表字段为 String id, String manId,String age,String remark;
    39. //拼装分页信息
    40. SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
    41. MongoDBPageModel pm=new MongoDBPageModel();
    42. pm.setPagesize(2);
    43. pm.setPagenumber(1);
    44. List<Order> orders = new ArrayList<>(); //排序
    45. orders.add(new Order(Direction.DESC, "age"));
    46. Sort sort = new Sort(orders);
    47. pm.setSort(sort);
    48. pageable.setPage(pm);
    49. //拼装关联信息
    50. LookupOperation lookupOperation = LookupOperation.newLookup().
    51. from("dogData").//关联表名
    52. localField("_id").//关联字段
    53. foreignField("manId").//主表关联字段对应的次表字段
    54. as("dogs");//查询结果集合名
    55. //拼装具体查询信息
    56. //次表
    57. Criteria ordercri = Criteria.where("dogs").not().size(0);//只查询有宠物的人
    58. ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    59. AggregationOperation match = Aggregation.match(ordercri);
    60. //主表
    61. Criteria qqq=Criteria.where("name").regex("文");//只查询名字中带有文的人
    62. AggregationOperation match1= Aggregation.match(qqq);
    63. //分页查询
    64. Aggregation aggregation = Aggregation.newAggregation(match1,lookupOperation,match,Aggregation.sort(pageable.getSort()),//排序
    65. Aggregation.skip(pageable.getPageNumber()>1?(pageable.getPageNumber()-1)*pageable.getPageSize():0),//pagenumber
    66. Aggregation.limit(pageable.getPageSize()));//pagesize
    67. //总数查询
    68. Aggregation counts = Aggregation.newAggregation(match1,lookupOperation,match).;
    69. int count = mongoTemplate.aggregate(counts, "manEntry", BasicDBObject.class).getMappedResults().size();
    70. List<BasicDBObject> results = mongoTemplate.aggregate(aggregation, "manEntry", BasicDBObject.class).getMappedResults();
    71. //查询出的结果集为BasicDBObject类型
    72. //解析过程
    73. for (BasicDBObject b :results
    74. ) {
    75. //转化为jsonobject对象
    76. JSONObject jsonObject = new JSONObject(b);
    77. String id = jsonObject.get("id").toString();
    78. Integer age = ((int) jsonObject.get("age"));
    79. String remark = jsonObject.get("remark").toString();
    80. //转化为jsonarray
    81. JSONArray dogs = jsonObject.getJSONArray("dogs");
    82. if (dogs.size() > 0) {
    83. for (int i = 0; i < dogs.size(); i++) {
    84. JSONObject job = dogs.getJSONObject(i);
    85. String dogId = job.get("id").toString();
    86. String manId = job.get("manId").toString();
    87. }
    88. }
    89. }
    90. }
    91. }

    4.在Controller中进行引入

    1. @Autowired
    2. private MongoTemplate mongoTemplate;

    带条件查询

    1. Query query = new Query();
    2. if (code!=0) {
    3. query.addCriteria(Criteria.where("buiness_core").is(code));//is:等于
    4. }
    5. // query.fields().exclude("details.details");//exclude:不需要查询这个字段
    6. List<Station> list = mongoTemplate.find(query, 对应实体类的名称.class);//fin:查询集合中所有的对象

    多表联查

    1. /**
    2. * 两表联查
    3. *
    4. * @return
    5. */
    6. @GetMapping("/DeviceAndStation")
    7. public Object findStudentAndGrade(String stationId){
    8. LookupOperation lookupOperation=LookupOperation.newLookup().
    9. from("t_wlw_station"). //关联从表名
    10. localField("station_id"). //主表关联字段
    11. foreignField("_id").//从表关联的字段
    12. as("DeviceAndStation"); //查询结果名
    13. //带条件查询可以选择添加下面的条件
    14. Aggregation aggregation=Aggregation.newAggregation(lookupOperation);
    15. List<Map> results = mongoTemplate.aggregate(aggregation,"t_device", Map.class).getMappedResults();
    16. //上面的student必须是查询的主表名
    17. System.out.println(JSON.toJSONString(results));
    18. return results;
    19. }

    分页查询

    后端代码:

    1. @Override
    2. public Page<StrategyComment> queryPage(StrategyCommentQuery qo) {
    3. // totalPage prePage nextPage
    4. Query query = new Query();
    5. Criteria criteria = new Criteria();
    6. if (qo.getStrategyId() != null) {
    7. criteria = Criteria.where("strategyId").in(qo.getStrategyId());
    8. query.addCriteria(criteria);
    9. }
    10. // 模糊匹配
    11. if (qo.getKeyword() != null) {
    12. String keyword = qo.getKeyword();
    13. String pattern = ".*" + keyword + ".*"; // 正则表达式
    14. criteria.orOperator(Criteria.where("strategyTitle").regex(pattern),Criteria.where("content").regex(pattern));// 多条件模糊查询
    15. query.addCriteria(criteria);
    16. }
    17. // totalCount
    18. long totalCount = mongoTemplate.count(query, StrategyComment.class);
    19. // 如果没数据,可以优化性能不用继续执行了
    20. if (totalCount == 0) {
    21. return Page.empty();
    22. }
    23. // data
    24. // 第一个参数 从 0 开始
    25. Sort orderBy = Sort.by(Sort.Direction.DESC, "createTime"); //倒序
    26. Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),orderBy);
    27. query.with(pageable);
    28. List<StrategyComment> data = mongoTemplate.find(query, StrategyComment.class);
    29. // 三个参数 List<T> content, Pageable pageable, long total
    30. return new PageImpl<StrategyComment>(data, pageable, totalCount);
    31. }

    前端代码:

    1. <div th:fragment="mongoPage" style="text-align: center;">
    2. <ul id="pagination" class="pagination"></ul>
    3. <script>
    4. //分页
    5. $(function () {
    6. var totalPages = [[${page.totalPages}]]
    7. var startPage = [[${page.pageable.pageNumber}+1]]
    8. $("#pagination").twbsPagination({
    9. totalPages: totalPages || 1,
    10. startPage: startPage || 1,
    11. visiblePages: 5,
    12. first: "首页",
    13. prev: "上页",
    14. next: "下页",
    15. last: "尾页",
    16. initiateStartPageClick: false,
    17. onPageClick: function (event, page) {
    18. $("#currentPage").val(page);
    19. $("#searchForm").submit();
    20. }
    21. });
    22. })
    23. </script>
    24. </div>

    多表联查

    1. @Test
    2. public void saveMany() {// 批处理(10万条数据1127)(100万条条数据测试75773)qps13197
    3. Long startTime = System.currentTimeMillis();
    4. List<Aqz> aqzList = new ArrayList<>();
    5. for (int i = 0; i < 1000000; i++) {
    6. Aqz aqz = new Aqz();
    7. int random = (int) (Math.random() * 2);
    8. aqz.setABoolean(random == 0 ? false : true);
    9. aqz.setCreateDate(new Date());
    10. aqz.setString("string2" + i);
    11. aqz.setAnInt(i + 20000);
    12. aqz.setADouble(Math.random() * 2);
    13. List list = new ArrayList<>();
    14. list.add("aaa2" + i);
    15. list.add("bbb2" + i);
    16. list.add("ccc2" + i);
    17. aqz.setList(list);
    18. aqzList.add(aqz);
    19. System.out.println(i);
    20. }
    21. mongoTemplate.insertAll(aqzList);
    22. Long endtTime = System.currentTimeMillis();
    23. Long resultTime = endtTime - startTime;
    24. System.out.println("[总共执行耗时]" + resultTime);
    25. }
    26. ###分页,范围,模糊,排序###########################################################@Test
    27. public void saveClazz() {// 添加课堂
    28. Clazz clazz = new Clazz();
    29. clazz.setClazzName("天天课堂3");
    30. mongoTemplate.insert(clazz);
    31. }
    32. @Test
    33. public void saveStudent() {// 添加学生
    34. String clazzName = "天天课堂";
    35. Query query = new Query(Criteria.where("clazzName").is(clazzName));
    36. Clazz clazz = mongoTemplate.findOne(query, Clazz.class);
    37. Student student = new Student();
    38. student.setStudentName("小红2");
    39. student.setAge(18);
    40. student.setClazzId(clazz.getId());
    41. mongoTemplate.save(student);
    42. }
    43. @Test
    44. public void findOneClazz() {
    45. Query query = new Query(Criteria.where("_id").is("60e10203d31e2641ecb748ee"));
    46. Clazz clazz = mongoTemplate.findOne(query, Clazz.class);
    47. // clazz】】】" + clazz);
    48. }
    49. @Test
    50. public void findByManyStudent1() {// 多条件1
    51. Query query = new Query();
    52. query.addCriteria(Criteria.where("studentName").is("小红"));
    53. query.addCriteria(Criteria.where("age").is(18));
    54. List students = mongoTemplate.find(query, Student.class);
    55. // students);
    56. }
    57. @Test
    58. public void findByManyStudent0() {// 多条件0
    59. Query query = new Query(Criteria.where("studentName").is("小红"));
    60. query.addCriteria(Criteria.where("age").is(18));
    61. List students = mongoTemplate.find(query, Student.class);
    62. // students);
    63. }
    64. @Test
    65. public void findByManyStudent3() {// 多条件3
    66. Query query = new Query(Criteria.where("studentName").is("小红").and("age").is(18));
    67. List students = mongoTemplate.find(query, Student.class);
    68. // students);
    69. }
    70. @Test
    71. public void findByManyStudent2() {// 多条件2
    72. Student student = new Student();
    73. student.setStudentName("小红");
    74. student.setAge(18);
    75. Query query = new Query(Criteria.byExample(student));
    76. List students = mongoTemplate.find(query, Student.class);
    77. // students);
    78. }
    79. @Test
    80. public void findByManyStudentOr() {// 多条件0 or
    81. Query query = new Query(Criteria.where("studentName").regex(""));
    82. query.addCriteria(new Criteria().orOperator(Criteria.where("age").is(18),
    83. new Criteria().andOperator(Criteria.where("studentName").is("小明"), Criteria.where("age").is(16))));
    84. List students = mongoTemplate.find(query, Student.class);
    85. // students);
    86. }
    87. @Test
    88. public void searchClazzByIn() {// in操作
    89. List str = new ArrayList<>();
    90. str.add("天天课堂");
    91. Query query = new Query(Criteria.where("name").in(str));
    92. List clazzList = mongoTemplate.find(query, Clazz.class);
    93. // clazzList】】】" + clazzList);
    94. }
    95. @Test
    96. public void findListStudentSort() {// 排序
    97. Query query = new Query();
    98. query.with(Sort.by(Sort.Direction.DESC, "age"));
    99. List<Student> students = mongoTemplate.find(query, Student.class);
    100. // students】】】" + students);
    101. }
    102. @Test
    103. public void findFenYeList() {// 分页
    104. // 设置分页参数
    105. Query query = new Query();
    106. int currentPage = 2;// 0,1相同
    107. int pageSize = 2;
    108. // 设置分页信息
    109. query.limit(pageSize);
    110. query.skip(pageSize * (currentPage - 1));
    111. // query.addCriteria(Criteria.where("clazzName").regex(""));
    112. List clazzes = mongoTemplate.find(query, Clazz.class);
    113. // clazzs】】】" + clazzes);
    114. }
    115. @Test
    116. public void update() {// 更新
    117. Query query = Query.query(Criteria.where("id").is("60e103fcd31e2615bcaf91ed"));// 添加查询条件
    118. // query.addCriteria(Criteria.where("time").gte(beginTime).lte(endTime));
    119. Update update = new Update();
    120. update.set("clazzName", "111");
    121. UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Clazz.class);
    122. // updateResult.toString());
    123. }
    124. @Test
    125. public void delete() {// 删除
    126. Query query = Query.query(Criteria.where("id").is("60e103fcd31e2615bcaf91ed"));
    127. mongoTemplate.remove(query, Clazz.class);
    128. }
    129. @Test
    130. public void findZongHe() {// 分页+范围+模糊查询+排序
    131. // 拼装查询信息
    132. Query query = new Query();
    133. query.addCriteria(Criteria.where("age").gte(6).lte(18));
    134. query.with(Sort.by(Sort.Direction.ASC, "age"));
    135. query.addCriteria(Criteria.where("name").regex("小"));
    136. // 模糊查询名字
    137. Long count = mongoTemplate.count(query, Student.class);
    138. // 查询总记录数
    139. List<Student> list = mongoTemplate.find(query, Student.class);
    140. }
    141. ####分组,两表三表联查###########################################################
    142. import com.csw.mongodbspringbootdemo.entity.Chair;
    143. import com.csw.mongodbspringbootdemo.entity.Desk;
    144. import com.csw.mongodbspringbootdemo.entity.Room;
    145. import com.mongodb.BasicDBObject;
    146. import org.junit.Test;
    147. import org.junit.runner.RunWith;
    148. import org.springframework.beans.factory.annotation.Autowired;
    149. import org.springframework.boot.test.context.SpringBootTest;
    150. import org.springframework.data.domain.Sort;
    151. import org.springframework.data.mongodb.core.MongoTemplate;
    152. import org.springframework.data.mongodb.core.aggregation.Aggregation;
    153. import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
    154. import org.springframework.data.mongodb.core.aggregation.AggregationResults;
    155. import org.springframework.data.mongodb.core.aggregation.LookupOperation;
    156. import org.springframework.data.mongodb.core.query.Criteria;
    157. import org.springframework.data.mongodb.core.query.Query;
    158. import org.springframework.test.context.junit4.SpringRunner;
    159. import java.util.ArrayList;
    160. import java.util.List;
    161. import java.util.Map;
    162. import java.util.UUID;
    163. @SpringBootTest
    164. @RunWith(SpringRunner.class)
    165. public class RoomDeskRecommend {
    166. @Autowired
    167. private MongoTemplate mongoTemplate;
    168. @Test
    169. public void saveRoom() {// 添加房间
    170. Room room = new Room();
    171. room.setName("空房间2");
    172. room.setUnitCode(UUID.randomUUID().toString());
    173. mongoTemplate.save(room);
    174. Room room2 = new Room();
    175. room2.setName("空房间1");
    176. room2.setUnitCode(UUID.randomUUID().toString());
    177. mongoTemplate.save(room2);
    178. }
    179. @Test
    180. public void saveDesk() {// 添加桌子
    181. String roomName = "光明房间";
    182. String deskName = "5号桌子";
    183. Query query = new Query(Criteria.where("name").is(roomName));
    184. Room room = mongoTemplate.findOne(query, Room.class);
    185. Desk desk = new Desk();
    186. desk.setName(deskName);
    187. assert room != null;
    188. desk.setUnitCode(room.getUnitCode());
    189. mongoTemplate.save(desk);
    190. System.out.println(room);
    191. Query query2 = new Query(Criteria.where("name").is(deskName));
    192. Desk desk2 = mongoTemplate.findOne(query2, Desk.class);
    193. System.out.println(desk2);
    194. }
    195. @Test
    196. public void groupBy() {// group
    197. List<AggregationOperation> aggs = new ArrayList<>();
    198. // aggs.add(Aggregation.match(Criteria.where("name").is("log")));
    199. aggs.add(Aggregation.group("name").count().as("count"));
    200. aggs.add(Aggregation.project().and("_id").as("name").and("count").as("count"));
    201. Aggregation agg = Aggregation.newAggregation(aggs);
    202. AggregationResults<Map> results = mongoTemplate.aggregate(agg, Desk.class, Map.class);
    203. for (Map result : results) {
    204. System.out.println(result);
    205. }
    206. }
    207. @Test
    208. public void findMoreTable() {// 两表联查
    209. LookupOperation lookupOperation = LookupOperation.newLookup().from("room"). // 关联表名
    210. localField("unitCode"). // 主关联字段
    211. foreignField("unitCode").// 从表关联字段对应的次表字段
    212. as("rooms");// 查询结果集合名
    213. Criteria ordercri = Criteria.where("rooms").not().size(0);// 只查询有宠物的人
    214. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    215. AggregationOperation matchZi = Aggregation.match(ordercri);
    216. Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi);// 排序
    217. List<Map> results = mongoTemplate.aggregate(aggregation, "desk", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
    218. for (Map result : results) {
    219. System.out.println(result);
    220. }
    221. }
    222. @Test
    223. public void findMoreTable2() {// 两表联查
    224. LookupOperation lookupOperation = LookupOperation.newLookup().from("desk"). // 关联表名
    225. localField("unitCode"). // 主关联字段
    226. foreignField("unitCode").// 从表关联字段对应的次表字段
    227. as("desks");// 查询结果集合名
    228. Criteria ordercri = Criteria.where("desks").not().size(0);// 只查询有宠物的人
    229. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    230. AggregationOperation matchZi = Aggregation.match(ordercri);
    231. Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi);// 排序
    232. List<Map> results = mongoTemplate.aggregate(aggregation, "room", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
    233. for (Map result : results) {
    234. System.out.println(result);
    235. }
    236. }
    237. @Test
    238. public void findMoreTableZongHe() {// 两表联查
    239. int pageNumber = 2;// 0,1相同
    240. int pageSize = 2;
    241. // 拼装关联信息
    242. LookupOperation lookupOperation = LookupOperation.newLookup().from("room"). // 关联表名
    243. localField("unitCode"). // 主关联字段
    244. foreignField("unitCode").// 从表关联字段对应的次表字段
    245. as("ClazzStudents");// 查询结果集合名
    246. // 拼装具体查询信息
    247. // 次表
    248. Criteria ordercri = Criteria.where("ClazzStudents").not().size(0);// 只查询有宠物的人
    249. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    250. AggregationOperation matchZi = Aggregation.match(ordercri);
    251. // 主表
    252. Criteria qqq = Criteria.where("name").regex("号");// 只查询名字中带有文的人
    253. AggregationOperation matchFu = Aggregation.match(qqq);
    254. // 分页查询
    255. Aggregation aggregation = Aggregation.newAggregation(matchFu, lookupOperation, matchZi,
    256. Aggregation.sort(Sort.Direction.DESC, "name"),
    257. Aggregation.skip(pageSize > 1 ? (pageNumber - 1) * pageSize : 0), Aggregation.limit(pageSize));// 排序
    258. // Aggregation.skip(pageable.getPageNumber()>1?(pageable.getPageNumber()-1)*pageable.getPageSize():0),//pagenumber
    259. // 分页
    260. /*
    261. * Aggregation.skip(pageSize>1?(pageNumber-1)*pageSize:0);
    262. * Aggregation.limit(pageSize);
    263. */
    264. // Aggregation.group("name");
    265. // 总数查询
    266. Aggregation counts = Aggregation.newAggregation(matchFu, lookupOperation, matchZi);
    267. int count = mongoTemplate.aggregate(counts, Desk.class, BasicDBObject.class).getMappedResults().size();
    268. System.out.println("【count】" + count);
    269. List<Map> results = mongoTemplate.aggregate(aggregation, "desk", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
    270. for (Map result : results) {
    271. System.out.println(result);
    272. }
    273. }
    274. /*
    275. * public PageResult pagination(Class clazz, int pageSize, int pageNum,
    276. * Query query) { long total = this.mongoTemplate.count(query, clazz); Integer
    277. * pages = (int)Math.ceil((double)total / (double)pageSize); if (pageNum <= 0 ||
    278. * pageNum > pages) { pageNum = 1; } int skip = pageSize * (pageNum - 1);
    279. * query.skip(skip).limit(pageSize); List list = mongoTemplate.find(query,
    280. * clazz); PageResult pageResult = new PageResult(); pageResult.setTotal(total);
    281. * pageResult.setPages(pages); pageResult.setPageSize(pageSize);
    282. * pageResult.setPageNum(pageNum); pageResult.setList(list); return pageResult;
    283. * }
    284. */
    285. @Test
    286. public void saveChair() {// 添加椅子
    287. String roomName = "光明房间";
    288. String chairName = "1号椅子";
    289. Query query = new Query(Criteria.where("name").is(roomName));
    290. Room room = mongoTemplate.findOne(query, Room.class);
    291. Chair chair = new Chair();
    292. chair.setName(chairName);
    293. assert room != null;
    294. chair.setUnitCode(room.getUnitCode());
    295. mongoTemplate.save(chair);
    296. }
    297. @Test
    298. public void findMoreTable3_0() {// 三表联查测试,第一个表关联第二个人表(关联字段1),第一个表关联第三个表(关联字段1
    299. LookupOperation lookupOperation = LookupOperation.newLookup().from("desk"). // 关联表名
    300. localField("unitCode"). // 主关联字段
    301. foreignField("unitCode").// 从表关联字段对应的次表字段
    302. as("desks");// 查询结果集合名
    303. Criteria ordercri = Criteria.where("desks").not().size(0);// 只查询有宠物的人
    304. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    305. AggregationOperation matchZi = Aggregation.match(ordercri);
    306. LookupOperation lookupOperation2 = LookupOperation.newLookup().from("chair"). // 关联表名
    307. localField("unitCode"). // 主关联字段
    308. foreignField("unitCode").// 从表关联字段对应的次表字段
    309. as("chairs");// 查询结果集合名
    310. Criteria ordercri2 = Criteria.where("chairs").not().size(0);// 只查询有宠物的人
    311. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    312. AggregationOperation matchZi2 = Aggregation.match(ordercri2);
    313. Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi, lookupOperation2, matchZi2);// 排序
    314. List<Map> results = mongoTemplate.aggregate(aggregation, "room", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
    315. for (Map result : results) {
    316. System.out.println(result);
    317. }
    318. }
    319. // 数据模拟
    320. @Test
    321. public void findMoreTable3_1() {// 三表联查测试,第一个表关联第二个人表(关联字段1),第一个表关联第三个表(关联字段2
    322. LookupOperation lookupOperation = LookupOperation.newLookup().from("desk"). // 关联表名
    323. localField("unitCode"). // 主关联字段
    324. foreignField("unitCode").// 从表关联字段对应的次表字段
    325. as("desks");// 查询结果集合名
    326. Criteria ordercri = Criteria.where("desks").not().size(0);// 只查询有宠物的人
    327. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    328. AggregationOperation matchZi = Aggregation.match(ordercri);
    329. LookupOperation lookupOperation2 = LookupOperation.newLookup().from("chair"). // 关联表名
    330. localField("lastCode"). // 主关联字段
    331. foreignField("lastCode").// 从表关联字段对应的次表字段
    332. as("chairs");// 查询结果集合名
    333. Criteria ordercri2 = Criteria.where("chairs").not().size(0);// 只查询有宠物的人
    334. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    335. AggregationOperation matchZi2 = Aggregation.match(ordercri2);
    336. Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi, lookupOperation2, matchZi2);// 排序
    337. List<Map> results = mongoTemplate.aggregate(aggregation, "room", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
    338. for (Map result : results) {
    339. System.out.println(result);
    340. }
    341. }
    342. // 数据模拟
    343. @Test
    344. public void findMoreTable3_3() {// 三表联查测试,第一个表关联第二个人表(关联字段1),第二个表关联第三个表(关联字段2
    345. LookupOperation lookupOperation = LookupOperation.newLookup().from("room"). // 关联表名
    346. localField("unitCode"). // 主关联字段
    347. foreignField("unitCode").// 从表关联字段对应的次表字段
    348. as("rooms");// 查询结果集合名
    349. Criteria ordercri = Criteria.where("rooms").not().size(0);// 只查询有宠物的人
    350. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    351. AggregationOperation matchZi = Aggregation.match(ordercri);
    352. LookupOperation lookupOperation2 = LookupOperation.newLookup().from("chair"). // 关联表名
    353. localField("rooms.lastCode"). // 主关联字段
    354. foreignField("lastCode").// 从表关联字段对应的次表字段
    355. as("chairs");// 查询结果集合名
    356. Criteria ordercri2 = Criteria.where("chairs").not().size(0);// 只查询有宠物的人
    357. // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
    358. AggregationOperation matchZi2 = Aggregation.match(ordercri2);
    359. Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi, lookupOperation2, matchZi2);// 排序
    360. List<Map> results = mongoTemplate.aggregate(aggregation, "desk", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
    361. for (Map result : results) {
    362. System.out.println(result);
    363. }
    364. }
    365. }


     

  • 相关阅读:
    Java 变得越来越像 Rust?
    谈谈你对mvc和mvvm的理解
    删除字符串字符,使输出结果不包含回文串
    火车头采集器保存任意格式-免费火车头采集发布配置教程
    sql优化最新干货---mysql存储过程、索引和锁
    前端通过Blob或File文件获取二进制数据
    二叉树的遍历-树-数据结构和算法(Java)
    为零售业敲响警钟:关注行业数字化转型的未来趋势
    git初步使用
    基于SSM框架实现学生管理系统
  • 原文地址:https://blog.csdn.net/weixin_53998054/article/details/127516787