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

139
Views
Best way to run 1k+ queries on MongoDB and nodejs?

I'm trying to run approximately 1,000 queries on MongoDB to check for matches on particular object property.

Please shield your eyes from what is no doubt some extremely amateur code but would appreciate any ways to make this more efficient. It works but takes a long time.

'followers' is an array of Twitter user objects and it is being checked against a database of half a million records.


function checkFollowers(followers){
  // check if followers are in DB

  let matches = [];

  MongoClient.connect(url, function(err, db) {
    if (err) throw err;

    console.log("Connected!");

    async.each(followers, function(item, callback){

      var regex = new RegExp("^" + item.username + "$", 'i')

      dbo.collection("User").findOne({Username : {$regex : regex}},function(err, result) {

        if (err) throw err;

        if(result != null){
          matches.push(result.Username)
        }
,
        callback(null);

      });
    }, function(err){
        if(err) {
            console.log(err);
        } else {
            console.log('All records have been checked');
            db.close();
            console.log("This many matching records " + matches.length)
            console.log(matches)
        }
    });      
  });
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Maybe like this:

const allUsers = dbo.collection("User").find().toArray();
followers.forEach( follower => {
   var regex = new RegExp("^" + follower.username + "$", 'i')      
   if (allUsers.filter( aUser = > regex.test(aUser))) 
      matches.push(aUser.Username);
})

Reading the collection again and again does not make much sense.

Regular expressions are always slow, so you may prefer

dbo.collection("User").aggregate([
   {$set: {username_UC: { $toUpper: "$username" } } }
]).toArray();
followers.forEach( follower => {
   if (allUsers.filter( aUser => aUser.username_UC == follower.toUpperCase() )) 
      matches.push(aUser.Username);
})

Or even faster:

dbo.collection("User").aggregate([
   {$match: {$expr: { $in: [ { $toUpper: "$username" }, followers.map(x => x.toUpperCase()) ] } } }
])
about 4 years ago · Juan Pablo Isaza 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!