Example 1 — Sample Data
Imagine six products across books, stationery, and toys. We save them in a collection named products.
db.products.insertMany([
{ _id: 1, name: "Notebook", category: "stationery" },
{ _id: 2, name: "Pencil", category: "stationery" },
{ _id: 3, name: "Math Book", category: "books" },
{ _id: 4, name: "Story Book", category: "books" },
{ _id: 5, name: "Atlas", category: "books" },
{ _id: 6, name: "Yo-Yo", category: "toys" }
]); How the Data Is Stored in MongoDB
After the insert, MongoDB keeps six documents in products. Run find() to see them:
db.products.find() Tally by category:
| category | How many |
|---|---|
books | 3 |
stationery | 2 |
toys | 1 |
books ●●● (3)
stationery ●● (2)
toys ● (1)
$sortByCount ranks ●●● first How It Works
- Insert once.
insertManyadds six product documents. - Keep a category field. That is what we will group on.
- find() shows all rows. Ranking comes in Example 2.

