Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
MongoDB - Many counts using an array

How to make many counts using an array as input in Mongoose, and return an array

I am trying to use the code below but it is not working, list2 is returning as empty.

list = ['Ann', 'Bob', 'John', 'Karl'];
list2 = [];

for(let i = 0; i < list.length; i++) {
    Clients.count({name: list[i]}, function(err, doc){
        list2.push(doc);
    })
}
return list2
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You could run an aggregation pipeline as follows:

list = ['Ann', 'Bob', 'John', 'Karl'];
list2 = [];
Clients.aggregate([
    { "$match": { "name": { "$in": list } } },
    {
        "$group": {
            "_id": "$name",
            "count": { "$sum": 1 }
        }
    },
    {
        "$group": {
            "_id": null,
            "list2": {
                "$push": {
                    "name": "$_id",
                    "count": "$count"
                }
            }
        }
    }
]).exec(function(err, results) {
    list2 = results[0].list2;
    console.log(list2);
});
over 4 years ago · Santiago Trujillo Report

0

const async = require('async');

var list = ['Ann', 'Bob', 'John', 'Karl'];

async.map(list, function(item, callback) {
    result = {};
    Clients.count({name: item}, function(err, data) {
        result[item] = data || 0;
        return callback(null, result);
    });
}, function(err, data) {
    console.log(data);
});
over 4 years ago · Santiago Trujillo Report

0

Here's another way based on Med Lazhari's answer

const async = require('async');

var list = ['Ann', 'Bob', 'John', 'Karl'];

var counting = function (item, doneCallback) {
    var query = Clients.count({name: item});
    query.then(function (doc) {
      return doneCallback(null, doc);
    });  
  };

async.map(list, counting, function(err, data) {
    console.log(data);
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!