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