我正在尝试通过springData中的聚合来获取与众不同的product_id的计数。
文档看起来像这样
{
{'product_id':1,
'name' : hell
}
{
'product_id':1,
'name' : bajaj
}
{
'product_id':2,
'name':husky
}
}
我想返回一个long类型的变量计数。 这是我尝试处理的代码,但出现错误,无法将list <>转换为long。
Aggregation aggregation=newAggregation(match(criteria),group(FieldNames.PRODUCT_ID).count().as("count"),project("count"));
return mongoTemplate.aggregate(aggregation,PriceMappedProduct.COLLECTION_NAME,long.class).getMappedResult();
.
答案 0 :(得分:1)
您已经接近了,您可以这样做来获得计数:
选项1:
List<BasicDBObject> count = mongoTemplate.aggregate(aggregation,PristinePriceMappedProduct.COLLECTION_NAME,BasicDBObject.class).getMappedResult();
// mongoTemplate.aggregate is returning list hence the error.
if(count!=null){
return count.size();
} else{
return 0;
}
选项2 :(一个衬纸)
return mongoTemplate.aggregate(aggregation,PristinePriceMappedProduct.COLLECTION_NAME,BasicDBObject.class).getMappedResult();
// in this case make sure this function's return type is Integer or Long not int or long
注意:
在这种情况下,请确保函数的返回类型是Integer
或Long
而不是int
或long
,因为int
和long
是原始数据类型并且它们不包含null
。但是,如果没有数据,聚合逻辑可能会返回null
,因此使用Long或Integer(对象可以为null)