【发布时间】:2015-11-13 22:46:34
【问题描述】:
我有一个名为test 的集合。我想在test 集合中存在的所有文档中获得一个密钥的总量:sal。
这里是示例文档:
[
{
"name": "hari",
"sal": "100",
"status": "Y",
"address": "Bangalore"
},
{
"name": "Sam",
"sal": "200",
"status": "Y",
"address": "Bangalore"
},
{
"name": "Nik",
"sal": "200",
"status": "N",
"address": "Bangalore"
}
]
我尝试了以下查询:
db.getCollection('test').aggregate([{
$match: {
Status: "Y"
}
}, {
$group: {
_id: null,
total: {
$sum: "$sal"
}
}
}])
我得到了零。
谁能建议我正确的查询来在集合中的所有文档中添加特定键。
【问题讨论】:
-
听起来你的
sal字段实际上是一个字符串,或者至少不是数字,或者不存在。 -
您的查询乍一看似乎是正确的,但它可能不适合您的文档。请发布示例文档。
-
嗨 Philipp,下面是一些测试集合的示例文档 ******* test { "name": "hari", "sal":"100", "status": " Y”,“地址”:“班加罗尔”} {“姓名”:“山姆”,“萨尔”:“200”,“状态”:“Y”,“地址”:“班加罗尔”} {“姓名”:“ Nik", "sal":"200", "status": "N", "address": "Bangalore" } 同时运行聚合查询 db.getCollection('test').aggregate([{$match:{status :"Y"}},{$group:{_id:null,total:{$sum:"$sal"}}}])。我的价值为零。
-
根据您的文档结构
sal看起来像string数据类型,所以您应该将sal数据类型更改为Int or Float了解更多如何转换数据类型检查this link
标签: mongodb aggregation-framework