Count Group Items
In this step, we'll explore different ways to count items within groups using MongoDB's aggregation framework. Counting is a fundamental operation that helps you understand the distribution of your data.
Let's continue working with our salesdb
database:
// Ensure we're in the correct database
use salesdb
First, let's add more products to make our counting more interesting:
db.products.insertMany([
{ category: "Electronics", brand: "Apple" },
{ category: "Electronics", brand: "Samsung" },
{ category: "Clothing", brand: "Nike" },
{ category: "Clothing", brand: "Adidas" },
{ category: "Books", brand: "Penguin" },
{ category: "Books", brand: "Oxford" }
]);
Now, let's count items in different ways:
- Count the number of products in each category:
db.products.aggregate([
{
$group: {
_id: "$category",
productCount: { $sum: 1 }
}
}
]);
- Count unique brands within each category:
db.products.aggregate([
{
$group: {
_id: "$category",
uniqueBrands: { $addToSet: "$brand" }
}
}
]);
- Count the number of unique brands and total products:
db.products.aggregate([
{
$group: {
_id: "$category",
totalProducts: { $sum: 1 },
uniqueBrands: { $addToSet: "$brand" },
brandCount: { $addToSet: "$brand" }
}
},
{
$project: {
totalProducts: 1,
uniqueBrandCount: { $size: "$uniqueBrands" }
}
}
]);
Example Output
[
{
_id: 'Electronics',
totalProducts: 4,
uniqueBrandCount: 2
},
{
_id: 'Clothing',
totalProducts: 4,
uniqueBrandCount: 2
},
{
_id: 'Books',
totalProducts: 4,
uniqueBrandCount: 2
}
]
Key aggregation operators explained:
$sum: 1
: Counts the total number of documents in each group
$addToSet
: Creates an array of unique values
$size
: Counts the number of elements in an array