0

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, :)

randunel
  • 8,917
  • 1
  • 26
  • 24
ParisNakitaKejser
  • 12,112
  • 9
  • 46
  • 66

1 Answers1

3

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.

Mark Embling
  • 12,605
  • 8
  • 39
  • 53
  • This only works if he is using the node-mongodb-native driver. If he is using a wrapper such as Mongoose, he needs to access the underlying driver to use `toArray` and `each` – randunel Aug 03 '13 at 08:22
  • This is true. I made the assumption he was, based on the fact he refers to the stream function (which the native driver has), and the lack of any further information. – Mark Embling Aug 03 '13 at 08:27
  • Thanks a lot, the "find().each(...) function its what there resolved med problem ^^ – ParisNakitaKejser Aug 05 '13 at 07:30