I want to count the number of documents of each movie in the MotherCard collection:
const list = ['Frozen 2013', 'Oblivion 2013', 'Avatar 2009'];
const count = await db.MotherCard.countDocuments({ movie: { $in: list }});
console.log(count)
But it only returns the number of documents of the first array element (‘Frozen 2013’).
How can we count documents count of all of the list ?
>Solution :
I think this can be implemented using MongoDB’s aggregation pipeline.
const list = ['Frozen 2013', 'Oblivion 2013', 'Avatar 2009'];
const result = await db.MotherCard.aggregate([
{ $match: { movie: { $in: list }}},
{ $group: { _id: "$movie", count: { $sum: 1 }}}
]).exec();
console.log(result);
and the result will look like this:
[
{ "_id" : "Frozen 2013", "count" : 10 },
{ "_id" : "Oblivion 2013", "count" : 10 },
{ "_id" : "Avatar 2009", "count" : 10 }
]