I have a list of posts:
[{"name: "POST 1", {"name": "POST 2",}, {"name": "POST 1",}
I want to count the number of identical names and output the maximum number. The expected result is: {"id: "POST 1", count:2}
Now I wrote this query
db.Posts.aggregate([
{$group: { _id: "$post.name", count: { $sum: 1 } }
])
The output I get is: [{"id: "POST 1", count:2}, {"id: "POST 1", count:1}]. How can I now get the maximum from this list? Without using sort and limit, because there may be several identical min.
2
Answers
Here’s one way to get all the most frequent
"name"
values with their count.Try it on mongoplayground.net.
One more option (a variation on @rickhg12hs’ s answer) is using
$setWindowFields
, since$facet
requires to group all your documents into one large document, and a document have a size limit:See how it works on the playground example