I would like to know how many documents are going to be processed by my MongoDB cursor before I iterate over the cursor. Do I have to run the query twice, or can I determine the size of a cursor and then iterate over the cursor without running the query twice?
myCount = myCollection.find({complex query}).count(); // will get my count
myCursor = myCollection.find({complex query}); // will get my cursor for iteration
but these two commands will run the query twice, which is presumably inefficient?
What is the most efficient way to determine the number of documents that I will iterate over without running the query twice? My docs are quite large.
Does MongoDB 'know' how many docs are going to be returned before it starts returning them via the cursor? Where can I read up on Mongo internals for this info?
I am running this within node, and I'm using the standard MongoDB node driver. So, the solution needs to deal with the usual node callback mechanisms etc, etc.
Thanks
EDIT
I have amended the original question to state I'm using the node driver
EDIT2
yogesh's answer is correct, I just needed to figure out the syntax for node. I've shown the working code below in case it helps anyone
db.collection('collectionName', function(err, collection) {
function processItem(err, item) {
if (item === null) {
db.close();
callback(null, {info: "yippee"});
return;
}
cursor.nextObject(processItem); // continue looping
}
var cursor = collection.find({foo:1});
cursor.count(function(err,count){
console.log('resultCursor size='+count);
cursor.nextObject(processItem); // Start of the loop
});
}