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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With