当前位置:   article > 正文

mongo+java 连表排序、条件、分页查询问题_addfieldsoperation

addfieldsoperation

*注释:mongo 连表查询条件----mongoDB版本3.2以上

开始之前先说一下我的背景吧。做一个管理系统类似的项目,因为项目是借鉴了其他公司的项目,所以数据库也沿用了。因为mongoDB跟mysql不同,它是文档型数据库,单表是随心所欲的,但是涉及到多表操作就有点懵了。不过嘛,秉着不畏艰难的信念,然后,就开始了,哈哈。


1、软件版本

  • mongoDB:4.2.1(命令:db.version();noSqlBootster可以直接执行)
  • springBoot统一版本:2.3.2

2、步骤

连表条件:两个表联合查询,用从表的某个字段排序,从表查询条件,分页

  • 1、关联表:

  • LookupOperation lookup = LookupOperation.newLookup().from("base_users").localField("user_id").foreignField("_id").as("user"); 
    
    • 1
  • 斜体样式*base_user是从表,localField里面是主表里面关联 base_user的字段,oreignField里面是从表的字段

  • 关联字段数据看类型需要完全一致,不一致需要转换:

  • AddFieldsOperation addFieldsOperation = AddFieldsOperation.addField("user_id").withValue(ConvertOperator s.ToObjectId.toObjectId("$user_id")).build();
    
    • 1
  • 2、查询

  • 查询行数:

  • Aggregation countAgg = Aggregation.newAggregation(
             Aggregation.match(criteria),
             addFieldsOperation,
             lookup,
             Aggregation.group("_id:null").count().as("count")
     );
     AggregationResults<Map> resultCount = mongoTemplate.aggregate(countAgg, "base_role", Map.class);
     List<Map> countList = resultCount.getMappedResults();
     long count = 0L;
     if (countList.size() > 0) {
         count = Long.parseLong(countList.get(0).get("count").toString());
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 查询具体数据

  • //查询具体数据
    Aggregation agg = Aggregation.newAggregation(
            Aggregation.match(criteria),
            addFieldsOperation,
            lookup,
            Aggregation.unwind("user"),
            Aggregation.project("_id", "user_id", "name", "created_at", "created_by", "updated_at", "updated_by")
                    .andInclude("user.name", "user.age"),
            Aggregation.sort(Sort.Direction.ASC, "age"),
            Aggregation.skip(pageable.getOffset()),
            Aggregation.limit(pageable.getPageSize())
    );
    AggregationResults<BaseRole> subFields = mongoTemplate.aggregate(agg, "base_role", BaseRole.class);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    查询条件自定义,可以直接使用从表user.属性方式直接参与查询

好了,到这里就大功告成了。最后说一下我踩了的坑吧,agg里面放的顺序对查询结果是会有影响的,具体的可以看官网文档或者百度。

欢迎各位大佬提出宝贵的意见!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/56054
推荐阅读
相关标签
  

闽ICP备14008679号