能否请您帮忙改正这个查询,将其归类并计算为 洲际 基于 PIB 值大于和小于1.3?
db.collection.aggregate([
{
$project:{
"item":1,
"PIB":1
}
},
{
$addFields:{
moreThan1.3:{
$cond:[
{
$gt:[
"$PIB",
1.3
]
},
1,
0
]
},
lessThan1.3:{
$cond:[
{
$lte:[
"$PIB",
1.3
]
},
1,
0
]
}
}
},
{
$group:{
"_id":"$Continente",
"countSmaller":{
$sum:"$lessThan1.3"
},
"countBigger":{
$sum:"$moreThan1.3"
}
}
}
]).pretty()
这个错误出现了。
错误: 第10行: Unexpected number: 第10行: 意外的数字
谢谢您!请您帮助纠正这个查询,将 "Continental "的 "PIB "大于或小于1.3的数据进行分组和统计。
试试这个聚合查询 :
db.collection.aggregate([
{
$group: {
_id: "$continente",
/** counting docs based on condition, for an on-going doc if condition is met pass in 1 or 0 */
countSmaller: { $sum: { $cond: [{ $lte: ["$PIB", 1.3] }, 1, 0] } },
countBigger: { $sum: { $cond: [{ $gt: ["$PIB", 1.3] }, 1, 0] } }
}
}
]);
测试: db.getCollection(01MBIG - Actividad 1'.aggregated([ { $...
我已经更新了查询,你很接近,我用的是 $addFields
来存储该字段。
db.collection.aggregate([
{
$project:{
"item":1,
"PIB":1
}
},
{
$addFields:{
moreThan10:{
$cond:[
{
$gt:[
"$PIB",
10
]
},
1,
0
]
},
lessThan10:{
$cond:[
{
$lte:[
"$PIB",
10
]
},
1,
0
]
}
}
},
{
$group:{
"_id":"$Continente",
"countSmaller":{
$sum:"$lessThan10"
},
"countBigger":{
$sum:"$moreThan10"
}
}
}
]).pretty()
希望这能帮到你:)
更新
db.collection.aggregate([
{
$project:{
"item":1,
"PIB":1
}
},
{
$addFields:{
"moreThan1.3":{
$cond:[
{
$gt:[
"$PIB",
1.3
]
},
1,
0
]
},
"lessThan1.3":{
$cond:[
{
$lte:[
"$PIB",
1.3
]
},
1,
0
]
}
}
},
{
$group:{
"_id":"$Continente",
"countSmaller":{
$sum:"$lessThan1.3"
},
"countBigger":{
$sum:"$moreThan1.3"
}
}
}
]).pretty()