12

I am attempting to interface with MongoDB through Node.js and am having some trouble with the count() method. I am using node-mongodb-native and it looks like what I am doing should work. My code sample:

var get_total_num_docs = function(db_client, query, cb){
  db_client.collection(query['collection'], function(e, coll) {
    coll.find(query.params, query.options, function (e, cursor) {
      cursor.count(function (e, count) {
        console.log(count);
        return cb(e, count);
      });
    });
  });
};

I am sure that everything exists (aka coll and cursor are both defined), but it only works if my query.params field is empty (i.e. finding the count of an entire collection). So if I am trying to run a find with any kind of selector, the find works, but then it refuses to count on the returned cursor. From what I've read online this looks like the correct way to do it, but obviously something is wrong. Thanks for any and all help!

MrJaeger
  • 1,606
  • 3
  • 15
  • 14
  • What do you mean when you say it refuses to count? Is it giving you the wrong count or throwing an error? – Tim Gautier Feb 16 '12 at 20:24
  • As in it literally just never finishes, aka the callback passed to count is never called. I've run it for around 10 minutes and it just never finishes. The coll.find call takes a very short amount of time, but something just isn't working with the count. – MrJaeger Feb 16 '12 at 20:26
  • Have you tried ``console.log``ging each error object you receive? And what are the query parameters and options being used? –  Feb 16 '12 at 22:05
  • without the actual parameters passed in it's hard to understand what's going on. you should also print out any errors that you are getting. Sometimes these issue are related to people closing the db before the query finished – christkv Feb 20 '12 at 11:51
  • Take a look at this post - very similar method to get the count. http://stackoverflow.com/questions/25473650/mongodb-get-the-number-of-documents-count-in-a-collection-using-node-js – Matt Aug 19 '15 at 15:40
  • What about using `db.collection.stats()`, it does return objects count ? – Risto Novik Sep 18 '16 at 19:00

1 Answers1

25

If you don't need a cursor, you should write your code like this:

var get_total_num_docs = function(db_client, query, cb){
  db_client.collection(query['collection'], function(e, coll) {
    coll.find(query.params, query.options).count(function (e, count) {
      console.log(count);
      return cb(e, count);
    });
  });
};
Aleksandar Vucetic
  • 14,715
  • 9
  • 53
  • 56