MongoDB Aggregation Framework - $sortByCount stage

💝$sortByCount stage:

The $sortByCount stage is used to group the incoming documents based on the specified expression and computes the number of documents in each distinct group.

💧 Syntax: 

{ $sortByCount: <expression> }

It is equivalent to $group + $sort stages.

{ $group: { _id: <expression>, count: { $sum: 1 } } },
{ $sort: { count: -1 } }


Each output document contains two fields; one is _id and another is count.

We can use the incoming document field as an expression or we can also use the $mergeObject expression to $sortByCount stage.

{ $sortByCount: { $mergeObjects: [ "$employee", "$business" ] } }

💧 Example:
db.persons.aggregate([
{$sortByCount: "$gender"}
]);

👉 Output:
    "_id" : "female", 
    "count" : 507.0
}
// ----------------------------------------------
    "_id" : "male", 
    "count" : 493.0
}

Post a Comment

Previous Post Next Post