Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Count MongoDB collection row

Count MongoDB collection row

Problem

I want to know how i can get a count of all the rows i get out of my MongoDB Collection.

var collection = db.collection( _collection ).find();

Right now i don't know about there are somting or not in it, if need to follow on how maney rows i get out from my collection.

are there somene better way for me to get my "data" out widtout using the Stream function?

var stream = collection.find().stream();            
stream.on("data", function(item)
{
    console.log(item.zipcode);
});

stream.on("end", function()
{
});

how i can get a kind of help, :)

Problem courtesy of: ParisNakitaKejser

Solution

I've not used the Node.JS driver at all, but looking at the documentation, it appears that Collection() has a count function on it:

// Assuming DB has an open connection...
db.collection("my_collection", function(err, collection) {
    collection.count(function(err, count)) {
        // Assuming no errors, 'count' should have your answer
    }
});

Does that help at all?

As for the second part of your question, I'm not entirely sure what you're asking but here are a couple of ways of getting your data:

Using the toArray() function to give you an array of all documents (see docs):

collection.find().toArray(function(err, docs) {
    // 'docs' should contain an array of all your documents
    // 'docs.length' will give you the length of the array (how many docs)
});

Using the each() function to loop over the results and execute the given function for each one (see docs):

collection.find().each(function(err, doc) {
    // this function will be executed once per document

    console.log(doc.zipcode)
});

I hope that helps you out.

Solution courtesy of: Mark Embling

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Count MongoDB collection row

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×