Mongo查询list数组中一个字段大于特定条数


由于刚刚接触mongodb,很多语法还不是很了解,写的不好的地方请大佬指出

查询的demo数据

 

{
  "_id":Object("xxxxxxxx"),
  "contentList":[
      "id":"xxxx",
      "type":2   
  ],
   [
      "id":"xxxx",
      "type":2   
  ]
 
}  

  

 

查询方法,使用聚合aggregate查询

match:将查询的contentList的size大于2的查出来

unwind:将集合根据contentList分组

match:再查出所有contentList的type为2的结果

group:再根据_id和total分组,total根据_id计算总数

match:过滤掉contentList的type小于3条的数据

project:结果集过滤,我只要id字段

db.getCollection('momPublishRecently').aggregate([
     {"$match": {"contentList.2": {"$exists": 1}}},
     {"$unwind": "$contentList"},
     {"$match": {"contentList.type": 2}},
     {"$group": {"_id":"$_id", "total": {"$sum":1}}},
     {"$match": {"total": {"$gte": 3}}},
     {"$project": {"total":0}}
     ]);

 

下面是springboot中的写法

 Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("contentList.2").exists(true)),
                Aggregation.unwind("contentList"),
                Aggregation.match(Criteria.where("contentList.type").is(2)),
                Aggregation.group("_id").count().as("total"),
                Aggregation.match(Criteria.where("total").gte(3)),
                Aggregation.project("_id")
        );
        AggregationResults<IdDTO> results = getMongoTemplate().aggregate(agg, "表名", IdDTO.class);
        List<IdDTO> list = results.getMappedResults();
        List<ObjectId> idList = new ArrayList<>();
     //这里转成object类型 if (!list.isEmpty()) { list.stream().forEach(idDTO -> { idList.add(new ObjectId(idDTO.getId())); }); }

  

刚刚接触就要求写这样的,还是有点吃力的,花了不少时间,踩了不少mongo的坑

感谢以下资料:

https://www.cnblogs.com/zhoujie/p/mongo1.html

https://docs.spring.io/spring-data/mongodb/docs/2.0.5.RELEASE/reference/html/#mongo.aggregation


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 MVC ValidationAttribute 验证一个字段必须大于另一个字段 mysql中一个字段升序,另一个字段降序【转】 oracle分组后合并其中一个字段 (2) Hibernate(JPA ) 查询返回只有一个字段,返回类型设置为List,取值报错 MySQL中设置同一张表中一个字段的值等于另一个字段的值 sql查询一个字段中包含逗号","的个数 mysql 同一个表中,查询出一个字段相同,一个字段不同的记录 SQL 分组后获取其中一个字段最大值的整条记录 sql根据某一个字段重复只取第一条数据 mysql,给每一条数据的某一个字段生成不同的随机数
 
粤ICP备18138465号  © 2018-2026 CODEPRJ.COM