$sortByCount vs $group

What is the difference between sort by count and group with a sum accumulator and descending sort

None.

See https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/, in particular, the section Behaviour.

They basically say it’s identical…

If a sort by count is explained

var pipeline = [ {$sortByCount:"$_id"} ]
db.coll.explain().aggregate(pipeline)

You’ll see something like this:

		{
			"$group" : {
				"_id" : "$_id",
				"count" : {
					"$sum" : {
						"$const" : 1
					}
				}
			}
		},
		{
			"$sort" : {
				"sortKey" : {
					"count" : -1
				}
			}
		}

$_id it’s not very original but it’s just any field can be used.

So yes, they are almost identical to $sum and descending $sort, it just saves typing.

1 Like