When you use the for in statement in java script, it iterates the enumerable
properties of an Object
.
db.x.find()
returns you a cursor Object.
Some of the enumerable
properties of the Cursor
are as below:
_mongo
_db
_collection
_ns
_query
_fields
_limit
_skip
_batchSize
_options
_cursor
_numReturned
_special help clone
_ensureSpecial
hasNext
map
forEach
In total there are 49
such properties of a Cursor
. That is why you always get 49 as a result irrespective of whether you iterate an empty collection or a collection with more than 1000 records. You are iterating these properties and not the results in the cursor.
If you notice these enumerable properties, you can find hasNext
, map
, forEach
functions as properties
of the cursor. So you need to make use of these properties to iterate the cursor.
To iterate the results in a Cursor:
var myCursor = db.x.find();
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
or,
db.x.find().forEach(function(i){
})
or,
db.x.find().map(function(i){
...
})
the first being the preferred and documented way.