mongotemplate聚合操作 - Specified class is an interface

这是我在使用MongoTemplate时使用管道操作unwind发生的,一开始我以为是返回的对象有问题,无法映射上去。实际上,使用unwind确实是带来数据结构的变化,例如:

{
    "_id" : ObjectId("5951ca15567ebff0d5011fbb"),
    "name" : "陈晓婵",
    "address" : "北京朝阳",
    "lunch" : [ 
        {
            "food" : "baozi",
            "fruit" : "taozi"
        }, 
        {
            "food" : "miaotiao",
            "fruit" : "xigua"
        }
    ]
}
-------------------------拆分前后--------------------------
{
    "_id" : ObjectId("5951ca15567ebff0d5011fbb"),
    "name" : "陈晓婵",
    "address" : "北京朝阳",
    "lunch" : {
        "food" : "baozi",
        "fruit" : "taozi"
    }
}
 
/* 2 */
{
    "_id" : ObjectId("5951ca15567ebff0d5011fbb"),
    "name" : "陈晓婵",
    "address" : "北京朝阳",
    "lunch" : {
        "food" : "miaotiao",
        "fruit" : "xigua"
    }
}  

可以看到lunch属性原来是一个数组/集合,后来变成了对象,这就是问题所在。
所以如果unwind查询的对象和返回的对象的数据结构是不同的,我们应该声明两个类分别能符合前后两个对象。在mongoTemplate.aggregate(agg, “dc_core_report”, ReportUnwindVo.class)这个方法中,第一个参数就是管道对象,第二是操作的mongodb的集合名称(原始对象),第三个是查询结果映射对象(结果对象)。具体代码如下:

List<ReportVo> result = new ArrayList<>();
Aggregation agg = Aggregation.newAggregation(
	Aggregation.unwind("columns"),
	Aggregation.match(Criteria.where("appId").is(appId)),
	Aggregation.match(new Criteria().orOperator(
	Criteria.where("columns._id").is(new ObjectId(colId)), 
	Criteria.where("columns._id").is(colId))
	)
);
AggregationResults<ReportUnwindVo> results = mongoTemplate.aggregate(agg, "dc_core_report", ReportUnwindVo.class);
List<ReportUnwindVo> reportEntityList = results.getMappedResults();
if(!CollectionUtils.isEmpty(reportEntityList)) {
	//result = reportMapper.toVoList(reportEntityList);
}
return result;

而且,这个内嵌文档查询id需要用 columns._id 这种方式,columns.$id这种方式不起作用。另外,我这里查id有时需要用new ObjectId将id格式化一下是因为业务保存id的时候有时候是纯粹的字符串,有时候是ObjectId。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值