MongoDB聚合使用$match和$group,$sum。

huangapple go评论75阅读模式
英文:

MongoDB aggregation with $match and $group, $sum

问题

我正在尝试查询内部类的总和。我根据我在互联网上找到的内容将它组合在一起,但目前我得到的是一个空响应。我不太确定出了什么问题,因为我试图将不同部分组合在一起。

我不能创建任何自定义类,只能使用@Aggregation方法。

@Aggregation("{ $match: { 'object': $object, $and: [{'end': {$ne: null}}] } }, { '$group': { 'object': $object, 'object__price': { $sum: $object.price } } }")
Integer sumPrices(@Param("$object") Object object);

(代码中参数的名称是随机的。)

我正在尝试查询与对象名称匹配且生产值 ('end') 不为null的所有项目。然后,我想获取该类型的所有对象的总和并返回总和值。价格值是一个内部类。

英文:

I'm trying to query the sum of an inner class. I put it together with what I've found on the internet but I am getting an empty response at the moment. Not quite sure what is wrong with it, since it's different parts that I've tried to put together.

I cannot create any custom classes and I can only use the @Aggregation method.

@Aggregation(" { $match:  { 'object':  $object, $and: [{'end': {$ne: null}}] } }, { '$group' : { 'object' : $object, 'object__price': { $sum: $object.price }}}")
    Integer sumPrices(@Param("$object") Object object);

(The names for the parameters are random in the code.)

I am trying to query for all items that match the object name and whose production value ('end') is not null. I then want to get the sum of all the objects of that types and return the sum value. Price value is an inner class.

答案1

得分: 0

尝试

    @Aggregation(" { $match:  { 'object':  $object, $and: [{'end': {$ne: null}}] } }, { '$group' : { 'object' : $object, 'object__price': { $sum: "$price" }, count: {$sum: 1}}}")

" $sum: "$price" " 会给出该对象类型中每个文档的价格键的总和,count 会给出这些文档的总数
英文:

Try

@Aggregation(" { $match:  { 'object':  $object, $and: [{'end': {$ne: null}}] } }, { '$group' : { 'object' : $object, 'object__price': { $sum: "$price" }, count: {$sum: 1}}}")

" $sum: "$price" " would give the sum of key price of each document that falls in that object type, and count would give the total count of such documents

huangapple
  • 本文由 发表于 2023年2月27日 19:24:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定