【问题标题】:MongoDB SUM Of 2 Columns2列的MongoDB总和
【发布时间】:2016-07-13 16:36:44
【问题描述】:

我的收藏中有以下文档:

{ "_id" : ObjectId("5785e5649b732ab238cfc519"), "name" : "Apple", "category" : "Fruit", "price" : 100, "discount" : 5 }
{ "_id" : ObjectId("5785e5709b732ab238cfc51a"), "name" : "Orange", "category" : "Fruit", "price" : 90, "discount" : 5 }
{ "_id" : ObjectId("5785e5819b732ab238cfc51b"), "name" : "PineApple", "category" : "Fruit", "price" : 60, "discount" : 2 }
{ "_id" : ObjectId("5785e5969b732ab238cfc51c"), "name" : "Potatto", "category" : "Vegetable", "price" : 10, "discount" : 1 }
{ "_id" : ObjectId("5785e5c39b732ab238cfc51d"), "name" : "Cabbage", "category" : "Vegetable", "price" : 5, "discount" : 1 }

及预期结果

{ "_id" : { "category" : "Vegetable" }, "total" : 15 }

我正在使用 mongoDB 查询来查找蔬菜类别的总和,如下所示

db.stall.aggregate([{$group: {_id: {category: "Vegetable" }, total: {$sum: "$price"}}}]);

但我得到以下结果

{ "_id" : { "category" : "Vegetable" }, "total" : 265 }

我应该如何找到蔬菜类别的总计和折扣列的总和。

【问题讨论】:

  • 您应该考虑显示带有预期输出而不是表格的示例文档。
  • 是的,我肯定会更新

标签: mongodb aggregation-framework


【解决方案1】:

我不确定我的问题是否正确,但这将过滤蔬菜类别的价格总和和折扣总和。

db.stall.aggregate([
   {
      {$match : {category : "Vegetable"}},
      {$group : {_id: "$category", sumOfTotal : {$sum : "$price"}, sumOfDiscount : {$sum : "$discount"}}}
   }
])

【讨论】:

  • 嗨,谭,感谢您的回答。我收到以下错误消息 SyntaxError: Unexpected token {
  • 感谢 Tan 它工作正常 :) group by 缺少“_id”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 2020-05-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多