spring-data mongodb aggregate 按照子文檔屬性分組用法

使用過程中遇到的坑,記錄一下

上例子:有個文檔結構如下


msg是個子文檔,裏面有LLKEYNAME字段。

需求:按照uin,和msg.LLKEYNAME分組,CreateTime在48小時以內,查詢出LLKEYNAME換成friendRemak這個名字

     List<AggregationOperation> aggs = new ArrayList<>();
         //aggs.add(Aggregation.match(Criteria.where("wxplaceid").is("123")));
    aggs.add(Aggregation.unwind("msg"));
         aggs.add(Aggregation.group("wxplaceid","msg.LLKEYNAME").count().as("receiveMsgCnt"));
         aggs.add(Aggregation.project()
                 .and("_id").as("id")
                 .and("wxplaceid").as("ownerwxplaceid")
                 .and("LLKEYNAME").as("friendRemark")
                 .and("receiveMsgCnt").as("receiveMsgCnt"));
         Aggregation agg = Aggregation.newAggregation(aggs);
         AggregationResults<TWechatMemberCrm> results = mongoTemplate.aggregate(agg,"tWechatMessage",TWechatMemberCrm.class);
         List<TWechatMemberCrm> list =  results.getMappedResults();

這裏有一個坑,就是在project()裏面取想要的字段的時候,注意LLKEYNAME前面不要加上msg. ,group的時候會默認把msg.去掉,然後project()再取

還有unwwind() 這個是必要的,意思是把msg文檔展開,如果不展開是不能 成功的

發佈了61 篇原創文章 · 獲贊 40 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章