I have a collection of Items with multiple documents stored in MongoDB. The structure is as follows:
{ id: 1, colour: red },
{ id: 2, colour: blue},
{ id: 3, colour: red },
{ id: 4, colour: green},
{ id: 5, colour: green}
I would like to count how many items are in the DB by colour. The result should be like this:
colour blue: 1
colour red: 2
colour green: 2
I would like to avoid the following two approaches since the records could be a really large number and as I can imagine, these would be inefficient and costly.
const items = await Item.find({ colour: {$in: ['red', 'blue', 'green']} });
items.forEach(item => {
// do the counting here
});
NEITHER
const blue = await Item.find({ colour: blue }).count();
const red = await Item.find({ colour: red }).count();
const green = await Item.find({ colour: green }).count();
The closest I found to my problem is this.
What is the best way to obtain these numbers?
Thanks for the help!!