how can i group by one field and sum fields in an object output structure preserved in mongodb?

For grouping in Mongodb, you should use aggregate():

db.collectionName.aggregate([
    {$match:{
        "word": "Casper"
    }},
    {
        $group:
        {
            _id:{
               "word" : "$word"
            },
            "som1" : {$sum:"$something.som1"},
            "som2" : {$sum:"$something.som2"}
        }
    },
    {
        $addFields:{
            "something":{
                "som1": "$som1",
                "som2": "$som2"
            }
        }
    },
    {
        $project:{
            "som1":0,
            "som2":0
        }
    }
])

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top