19

I'm very newbie on Javascript-NodeJS-MongoDB, I try to know the number of documents found by a query.

...
var page = req.params.page;  

var db = require('mongojs').connect('localhost:27017/foo', ['bar']); 

var docs = db.bar.find({x:'MME'}).sort({y:1}).skip(10*(page-1)).limit(10); 

var nbDocs = db.bar.find({x:'MME'}).count(); /*docs.count();*/

console.log(nbDocs);

But unfortunately the log gives me 'undefined', the same if I code

var nbDocs = docs.count();

Thank's a lot for your precious help.

Gilles.

1 Answers1

31

According to the docs the result will be in the second argument of the callback to the cursor.count() method. This might be a little more challenging to implement for somebody who's new to javascript, but I think something like this should work:

docs.count(function(error, nbDocs) {
    // Do what you need the count for here.
});
mayhewr
  • 4,003
  • 1
  • 18
  • 15
  • Thank's a lot for the solution. I have pleasure to learn Javascript, sorry that I can't vote up : Vote Up requires 15 reputation –  Oct 30 '12 at 23:51
  • @LeGilles Glad I could help. The accept is what most people forget, so you're ahead of the curve. ;) – mayhewr Oct 31 '12 at 00:07
  • hi ,i have an issue similar to above question, i want to push thw resultant count to an array can please help me to sought out of this, i have tried something like this but getting error`collection.find().count({},function(err,count){ console.log(count);//here iam getting the count,now i have to push this count to an array array.push({name:'Apple',count:count}) })` @mayhewr – Midhunsai Oct 28 '16 at 11:06
  • I haven't used mongodb or javascript in some time, but I'm guessing the fact that you're passing an object and a callback to the `.count()` method is the reason it's not working. Try `collection.find().count(function(err,count) { console.log(count); array.push({name:'Apple',count:count}) })` – mayhewr Oct 30 '16 at 00:34
  • This is the only solution for me in MongoDB server v3.4.4. Code of .find().count() does not work for some odd reason. – The Original Android Jun 10 '17 at 06:21