I have a collection called test. I want to get total amount of one key: sal across all documents present in the test collection.
Here is sample document:
[
{
"name": "hari",
"sal": "100",
"status": "Y",
"address": "Bangalore"
},
{
"name": "Sam",
"sal": "200",
"status": "Y",
"address": "Bangalore"
},
{
"name": "Nik",
"sal": "200",
"status": "N",
"address": "Bangalore"
}
]
and I tried the following query:
db.getCollection('test').aggregate([{
$match: {
Status: "Y"
}
}, {
$group: {
_id: null,
total: {
$sum: "$sal"
}
}
}])
I am getting zero.
Can anyone suggest me the right query to add a particular key across all the documents in a collection.
salfield is actually a string, or at least not a number, or non-existant.sallooks likestringdata type, so either you should changedsaldata type toInt or Floatfor more how to convert data type check this link