0

I am trying to group by and count with mongodb. Whatever I tried I couldn't do it. This is my query

db.getCollection("requests").find(
    {
        "updatedAt" : {
            "$gt" : ISODate("2020-05-14")
        },
        "status" : "SUGGESTED"
    },
    {
        "user.email" : 1.0,
        "user.name" : 1.0,
        "updatedBy.displayName" : 1.0,
        "requestTerm" : 1.0
    }
)

I would like to group and count based on updatedBy.displayName

So result will be for me distinct displayname ( Column1), count ( number of times )

How can I achieve this?

This is what I tried and it seems it doesn't work

db.requests.aggregate(
    {$match: {         "updatedAt" : {
            "$gt" : ISODate("2020-05-14")
        },
        "status" : "SUGGESTED" }},
    {$group: {updatedBy: "$updatedBy.displayName", number: {$sum: 1}}}
)
0

According to the mongo manual on $group, the command should be like this.

db.requests.aggregate(
    [
        {$match: {         
                "updatedAt" : {"$gt" : ISODate("2020-05-14")},
                "status" : "SUGGESTED" 
        }},
        {$group: {
            _id: {updatedBy: "$updatedBy.displayName"}, 
            number: {$sum: 1}
        }}
    ]
)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.