Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB get the number of documents (count) in a collection using Node.js

I'm currently writing a function that should return the number of documents from a collection the thing is that when i'm returning the value it says undefined, Here is my code:

    var MongoClient = require('mongodb').MongoClient;


// open the connection the DB server
var dbName = "ystocks";
var port = "27017";
var host = "localhost";
var tt = "mongodb://" + host + ":" + port + "/" + dbName;
//"mongodb://localhost:27017/ystocks"
function getNumOfDocs (collectionName, host, port, dbName) {
    var tt = "mongodb://" + host + ":" + port + "/" + dbName;
    count = 0;
    MongoClient.connect(tt, function (error, db){

        if(error) throw error;
        collectionName = collectionName;
        db.collection(collectionName).count({}, function(error, numOfDocs){
            if (error) throw error;

            //print the result
            console.dir("numOfDocs: " + numOfDocs);
            count = numOfDocs;
            console.log("count is : " + count);

            // close the DB
            return numOfDocs;
            db.close();


        });// end of count

    }); // Connection to the DB
    //return count;

} // end of getNumOfDocs


var ee = getNumOfDocs ("stocks", "localhost", "27017", "ystocks");
console.log("ee is " + ee);

Please help me.

like image 889
Alex Brodov Avatar asked Aug 24 '14 16:08

Alex Brodov


People also ask

How do I count the number of documents in MongoDB?

Description. n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB connection. n = count( conn , collection ,'Query', mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.

How do I count documents in a collection?

var value = db. collection. count(); and then print(value) or simply value , would give you the count of documents in the collection named collection .

How do you count data in node JS?

count() Method. The console. count() method is an inbuilt application programming interface of the console module which is used to count label passed to it as a parameter, by maintaining an internal counter for that specific label.


2 Answers

Here is how it should look like

var MongoClient = require('mongodb').MongoClient;

var dbName = "ystocks";
var port = "27017";
var host = "localhost";

function getNumOfDocs (collectionName, host, port, dbName, callback) {
    MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
        if(error) return callback(error);

        db.collection(collectionName).count({}, function(error, numOfDocs){
            if(error) return callback(error);

            db.close();
            callback(null, numOfDocs);
        });
    }); 
} 

And usage

getNumOfDocs("stocks", host, port, dbName, function(err, count) {
   if (err) {
       return console.log(err.message);
   }
   console.log('number of documents', count);
});

Keep in mind if you are going to call this function lots of times, it is better to just connect to the database once and then use the same connection.

like image 78
Barış Uşaklı Avatar answered Oct 21 '22 03:10

Barış Uşaklı


The use of count() is deprecated since mongodb 4.0.

Instead you should use documentCount() alternative, but is much moere slower than count() with large ammounts of data.

The alternatives are estimatedDocumentCount() that performs quite well and the usage is:

var MongoClient = require('mongodb').MongoClient;

var dbName = "ystocks";
var port = "27017";
var host = "localhost";

function getNumOfDocs (collectionName, host, port, dbName, callback) {
    MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
        if(error) return callback(error);

        db.collection(collectionName).estimatedDocumentCount({}, function(error, numOfDocs){
            if(error) return callback(error);

            db.close();
            callback(null, numOfDocs);
        });
    }); 
} 

Another option I use is to get the number of documents from the collection stats:

var MongoClient = require('mongodb').MongoClient;

var dbName = "ystocks";
var port = "27017";
var host = "localhost";

function getNumOfDocs (collectionName, host, port, dbName, callback) {
    MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
        if(error) return callback(error);

        db.collection(collectionName).stats(function(error, stats){
            if(error) return callback(error);

            db.close();
            callback(null, stats.count);
        });
    }); 
} 
like image 35
Dani Bizlogic Avatar answered Oct 21 '22 04:10

Dani Bizlogic