使用MongoDB汇总$ group获得百分比 [英] Get percentages with MongoDB aggregate $group
本文介绍了使用MongoDB汇总$ group获得百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从MongoDB聚合中的组管道中获取百分比。
我的数据:
< pre class = lang-js prettyprint-override>
{
_id:1,
名称:'hello',
类型:'big'
},
{
_id:2,
名称:'bonjour',
类型:'big'
},
{
_id :3,
名称:'hi',
类型:'short'
},
{
_id:4,
名称:'salut' ,
类型:'short'
},
{
_id:5,
名称:'ola',
类型:'short'
}
我的请求按类型分组,并计数:
[{
$ group:{
_id:{
type:'$ type'
},
count:{
$ sum:1
}
}
}]
结果:
[
{
_id {
type:'big',
},
count:2
},
{
_id {
type:'short ',
},
计算:3
}
]
但是我想有个计数和百分比,像这样:
[
{
_id {
type:'big',
},
数量:2,
百分比:40%
},
{
_id {
type:'short',
},
数:3,
百分比:60%
}
]
但是我不知道该怎么做。我尝试了 $ divide
等操作,但没有成功。
解决方案
好吧,我认为百分比
应该是字符串,如果值包含%
首先得到您将需要计数
文档数。
var nums = db.collection.count() ;
db.collection.aggregate(
[
{ $ group:{ _id:{ type: $ type}, count:{ $ sum:1}}},
{ $ project:{
count:1,
percentage:{
$ concat:[ { $ substr:[{ $ multiply:[{ $ divide:[ $ count,{ $ literal:nums}]},100]},0,2]},, %]}
}
}
]
)
结果
{ _id:{ type: short}, count:3, percentage: 60%}
{ _id:{ type: big}, count:2,% : 40%}
I'd like to get percentages from a group pipeline in a MongoDB aggregate.
My data:
{
_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'
}
My request group by type, and count:
[{
$group : {
_id : {
type : '$type'
},
"count" : {
"$sum" : 1
}
}
}]
Result:
[
{
_id {
type : 'big',
},
count : 2
},
{
_id {
type : 'short',
},
count : 3
}
]
But I'd like to have count AND percentage, like that:
[
{
_id {
type : 'big',
},
count: 2,
percentage: 40%
},
{
_id {
type : 'short',
},
count: 3,
percentage: 60%
}
]
But I've no idea how to do that. I've tried $divide
and other things, but without success. Could you please help me?
解决方案
Well I think percentage
should be string if the value contains %
First get you will need to count
the number of document.
var nums = db.collection.count();
db.collection.aggregate(
[
{ "$group": { "_id": {"type": "$type"}, "count": { "$sum": 1 }}},
{ "$project": {
"count": 1,
"percentage": {
"$concat": [ { "$substr": [ { "$multiply": [ { "$divide": [ "$count", {"$literal": nums }] }, 100 ] }, 0,2 ] }, "", "%" ]}
}
}
]
)
Result
{ "_id" : { "type" : "short" }, "count" : 3, "percentage" : "60%" }
{ "_id" : { "type" : "big" }, "count" : 2, "percentage" : "40%" }
这篇关于使用MongoDB汇总$ group获得百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文