MongoDB Aggregation Framework - $group stage

 💧 $group:

$group stage groups the documents in a collection that holds or shares the same data or criteria in one or more fields. It will make a group(s) with the document's distinct value.

For example, if we have 100 documents from which 40 documents hold the age is 50 and the salary is 40,000. 40 documents hold the age is 30, and salary is 30, 000. 10 documents hold the age is 40 and the salary is 25, 000. So the 3 groups will generate.

useful for:

counting, summing, averaging, and other calculation on grouped data.

Example:

db.persons.aggregate([{$group: {_id: "$eyeColor"}}]);

"_id": "green" }

// ----------------------------------------------

"_id": "blue" }

// ----------------------------------------------

"_id": "brown" }


For nested fields:

db.persons.aggregate([{$group: {_id: "$company.location.country"}}]);

"_id": "Italy" }

// ----------------------------------------------

"_id": "Germany" }

// ----------------------------------------------

"_id": "USA" }

// ----------------------------------------------

"_id": "France" }


Searching with multiple fields:

db.persons.aggregate([{$group: {_id: {age: "$age", eyeColor: "$eyeColor", fruit: "$favoriteFruit"}}}])

    "_id": {
        "age" : NumberInt(37), 
        "eyeColor": "blue", 
        "fruit": "apple"
    }
}
// ----------------------------------------------
    "_id": {
        "age" : NumberInt(29), 
        "eyeColor": "blue", 
        "fruit": "banana"
    }
}
// ----------------------------------------------
    "_id": {
        "age" : NumberInt(40), 
        "eyeColor": "green", 
        "fruit": "apple"
    }
}
// ----------------------------------------------
    "_id": {
        "age" : NumberInt(24), 
        "eyeColor": "green", 
        "fruit": "apple"
    }
}
// ----------------------------------------------

Post a Comment

Previous Post Next Post