【发布时间】:2019-06-24 20:25:59
【问题描述】:
我想从 MongoDB 聚合中的组管道中获取百分比。
我的数据:
{
_id : 1,
name : 'hello',
type : 'big'
},
{
_id : 2,
name : 'bonjour',
type : 'big'
},
{
_id : 3,
name : 'hi',
type : 'short'
},
{
_id : 4,
name : 'salut',
type : 'short'
},
{
_id : 5,
name : 'ola',
type : 'short'
}
我的请求按类型和计数分组:
[{
$group : {
_id : {
type : '$type'
},
"count" : {
"$sum" : 1
}
}
}]
结果:
[
{
_id {
type : 'big',
},
count : 2
},
{
_id {
type : 'short',
},
count : 3
}
]
但我想要计数和百分比,就像这样:
[
{
_id {
type : 'big',
},
count: 2,
percentage: 40%
},
{
_id {
type : 'short',
},
count: 3,
percentage: 60%
}
]
但我不知道该怎么做。我试过$divide 和其他东西,但没有成功。你能帮帮我吗?
【问题讨论】:
标签: mongodb aggregation-framework