theGreenCabbage
theGreenCabbage

Reputation: 4845

Iterating through all documents or objects in MongoDB

What is the command for displaying the n-th object/document in MongoDB?

Say I have 4000 objects stored in the database, and I want to loop through all 4000 of these objects to apply commands to them, I would do something like this:

for(i=0;db.foo.count();i++){
    do something
}

What should i be, with i being the first index. How do I iterate through all objects in MongoDB?

Upvotes: 0

Views: 2568

Answers (1)

Sushant Gupta
Sushant Gupta

Reputation: 9458

Here is the signature to find queries.

var cursor = collection.find(query, [fields], options);
cursor.sort(fields).limit(n).skip(m).each(function(err, doc) {});

For accessing n-th object use skip. Or for a batch after n-th object you can use limit and skip. For a large collection use stream.

Upvotes: 1

Related Questions