Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

aggregation framework - Get percentages with MongoDB aggregate $group

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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%" }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...