使用过程中遇到的坑,记录一下
上例子:有个文档结构如下
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文档展开,如果不展开是不能 成功的