I have some documents resembling the following structure:
{
"name": "item_1",
"category": ["a", "b"]
},
{
"name": "item_2",
"category": ["c"]
},
{
"name": "item_3",
"category": ["a", "c"]
},
{
"name": "item_4",
"category": ["a"]
},
{
"name": "item_5",
"category": ["a"]
}
I'm trying to get a sorted list of the most used values for the category field in all documents within the collection.
So in this example, the return value I'm expecting should be something like this:
[
{
"category": "a",
"count": 4
},
{
"category": "c",
"count": 2
},
{
"category": "b",
"count": 1
}
]
Is there a way to make such a query in mongoose?
Demo - https://mongoplayground.net/p/sBpwwvowXLH
Use aggregation query to $unwind your category into separate documents $group them back by category and get the count
db.collection.aggregate({
"$unwind": "$category"
},
{
"$group": {
"_id": "$category",
count: { $sum: 1 }
}
})