Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb, $sum on array of objects field [duplicate]

I am new to mongodb and may be I am missing something. But having a lot of samples in internet, still having problems to get a total on one field which is part of array of objects. Here is what I am doing:

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" }
    ]
  }
])

trying to get total amount in different ways:

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

getting the balance 0 instead of -2300

{ "_id" : null, "TotalBalance" : 0 }

same things with $unwind:

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

what I am doing wrong?

Thanks

like image 540
user9373387 Avatar asked Feb 17 '18 12:02

user9373387


1 Answers

You are storing amount as string whereas it should be a number if you want to use $sum operator. Try

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" }
    }
  }
])

According to MongoDB docs:

Calculates and returns the sum of numeric values. $sum ignores non-numeric values.

like image 188
mickl Avatar answered Nov 10 '22 01:11

mickl