This question already has answers here:
mongodb aggregate query isn't returning proper sum on using $sum

(2个答案)


3年前关闭。




我是mongodb的新手,可能是我缺少了一些东西。但是在互联网上有很多样本,仍然难以在一个对象数组的一个字段上获得总数。这是我在做什么:
db.collection.insertMany([
  {
    id: "6002010011500",
    balance: [
      { type: "PR", amount: "1000" },
      { type: "IN", amount: "300" }
    ]
  },
  {
    id: "5001010001005",
    balance: [
      { type: "PR", amount: "-3000" },
      { type: "IN", amount: "-600" }
    ]
  }
])

尝试以不同方式获取总金额:
db.collection.aggregate([
  {
    $group: {
      _id: null,
      TotalBalance: {
        $sum: "$balance.amount"
      }
    }
  }
])

得到余额0而不是-2300
{ "_id" : null, "TotalBalance" : 0 }

与$ unwind相同的事情:
db.collection.aggregate([
  { $unwind: "$balance" },
  {
    $group: {
      _id: null,
      TotalBalance: { $sum: "$balance.amount" }
    }
  }
])

我做错了什么?

谢谢

最佳答案

您将amount存储为字符串,但是如果要使用$sum运算符,则应为数字。尝试

db.collection.insertMany([
  {
    id: "6002010011500",
    balance: [
      { type: "PR", amount: 1000 },
      { type: "IN", amount: 300 }
    ]
  },
  {
    id: "5001010001005",
    balance:
      [
        { type: "PR", amount: -3000 },
        { type: "IN", amount: -600 }
      ]
  }
])

db.collection.aggregate([
  { $unwind: "$balance" },
  {
    $group: {
      _id: null,
      TotalBalance: { $sum: "$balance.amount" }
    }
  }
])

根据MongoDB的docs:

关于arrays - mongodb,对象数组上的$ sum字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48841269/

10-11 23:06
查看更多