mongodb,对象数组上的$ sum字段

use*_*387 2 arrays sum mongodb

我是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" }
    ]
  }
])
Run Code Online (Sandbox Code Playgroud)

尝试以不同的方式获取总金额:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      TotalBalance: {
        $sum: "$balance.amount"
      }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

获得余额0而不是-2300

{ "_id" : null, "TotalBalance" : 0 }
Run Code Online (Sandbox Code Playgroud)

$ unwind同样的事情:

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

我做错了什么?

谢谢

mic*_*ckl 5

您存储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" }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

根据MongoDB 文档

计算并返回数值的总和。$ sum忽略非数字值。