AAF
AAF

Reputation: 13

Mongodb.collection.count() is not accurate for collection.insertmany()

All, my code below is not giving me the correct number of rows, basically I am reading file data and storing it in mongodb collection; might be related to asynchronous vs synchronous operations? would appreciate if someone can point me to the right resource

collection.insertMany(jsonArray);

db.collection('collection1').count(function(function(err,count){
if(err) throw err;
console.log('Total Rows:' + count);
}

Total Rows: 3803

Now if I go to the mongodb command shell it gives me the accurate number of rows

Upvotes: 0

Views: 112

Answers (1)

prisoner_of_azkaban
prisoner_of_azkaban

Reputation: 758

Most probably you are trying to fetch the count before insert operation is complete. So, first wait for the data to be inserted and after that run the count query. Hope this helps.

Try this:

collection.insertMany(jsonArray, function(err, res) {
  if (err) {
   throw err;
  } else {
   db.collection('collection1').count(function(err, count) {
    if(err) throw err;
    console.log('Total Rows:' + count);
   })
  }
})

Upvotes: 1

Related Questions