V
V
Vitaly2021-09-02 14:13:42
MongoDB
Vitaly, 2021-09-02 14:13:42

How to get record count data broken down by a specific property in mongo db?

All the best! Please help me figure it out!
There are documents with a certain "interres" property of interest to me

[
    {"id": "001", "interres": "book", "otherProps": "...."},
    {"id": "002", "interres": "cinema", "otherProps": "...."},
    {"id": "003", "interres": "book", "otherProps": "...."},
    {"id": "004", "interres": "travel", "otherProps": "...."},
    {"id": "005", "interres": "book", "otherProps": "...."},
    {"id": "006", "interres": "cinema", "otherProps": "...."},
]


And now I'm trying to get something like this:
{books: 3pcs, cinema: 2pcs, travel: 1pcs}

Is it possible to get the number of documents by a certain property with one command with mongo db?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy, 2021-09-02
@Scorpiored88

Sorry, I kind of found
db.collection.aggregate([
{ $group: { _id: "$interres", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question