MongoDB - How can I get the size of a collection using Node.js?

11,765

.count() is an asynchronous function, just like .find() is.

Try the following code:

collection.count({}, function(error, numOfDocs) {
    console.log('I have '+numOfDocs+' documents in my collection');
    // ..
});

The first argument to .count() should be a search query. Since you want to count all documents, I'm passing an empty object {} as a search query.

Share:
11,765
Alex Brodov
Author by

Alex Brodov

Updated on July 26, 2022

Comments

  • Alex Brodov
    Alex Brodov almost 2 years

    I'm writing a server side code using node.js, I'm trying to get the MongoDB collection size using count method which is not working.

    This is my code

    var mongo = require('mongodb');
    var host =  "127.0.0.1";
    var port = mongo.Connection.DEFAULT_PORT;
    
    function getStock(name, callback) {
    
        var db = new mongo.Db("testDB", new mongo.Server(host, port, {}));
        db.open (function(error){
            console.log("We are connected! " + host + ":" +port);
    
            db.collection("stocks", function(error, collection){
                console.log("We have a collection");
                **var numOfDocs = db.collection('stocks').count()**
                **console.log("The num of  Docs in our collection is: ",numOfDocs)**
                collection.find({"name":name.toString()}, function(error, cursor) {
                    cursor.toArray(function(error, stocks) {
                        if (stocks.length==0) {
                            //console.log("No Stocks found!");
                            callback(false);
                        }
                        else {
                            callback(stocks[0]);
                            //console.log("Found a stock -> ",stocks[0]);
                        }
                    });
                });
    
    
            });
        });
    }
    
  • Alex Brodov
    Alex Brodov over 9 years
    What about the size() method?
  • Leonid Beschastny
    Leonid Beschastny over 9 years
    @user3502786 there is no size() method in MongoDB. You can use .stats() methods, but it's asynchronous too.
  • Leonid Beschastny
    Leonid Beschastny over 9 years
    @user3502786 the thing is, all io-related methods in node.js are asynchronous.
  • Alex Brodov
    Alex Brodov over 9 years
    Is it going to give me the same number?
  • Leonid Beschastny
    Leonid Beschastny over 9 years
    Yes. But it'll give you a lot of other information.
  • Alex Brodov
    Alex Brodov over 9 years
    So count will give me just an integer right? Hoe can i print the whole collection?
  • Leonid Beschastny
    Leonid Beschastny over 9 years
  • Zlatko
    Zlatko over 9 years
    To print the entire collection, fetch the entire collection.maybe you want to use some streaming lib for MongoDB though, if you have a lot of data.