Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count the number of documents of each movie in the list

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 }
]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading