How to correctly iterate through a search result in MongoDB-Shell?
Asked Answered
A

2

7

I have a MongoDB table containing 500 documents:

db.x.find().count()

Now I'd like to iterate over the all entries. Unfortunately the following code only gives 49, instead of 500:

a=0; for (s in db.x.find()) { a++; }; print(a);

I already increased the Number of results to 1000:

DBQuery.shellBatchSize = 1000

But that did not help.

Adel answered 19/1, 2015 at 22:48 Comment(1)
try db.x.find().forEach(function(item) {...})Orangewood
A
14

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.

Aubade answered 19/1, 2015 at 23:18 Comment(2)
Why the downvote? Comment so that the answer can be improved.Aubade
Your answer was perfect for me. My question also received 3 downvotes without a comment,...Adel
C
0

In my scenario, I wanted to use the old school For-loop, not forEach.

All works as expected for me if we simply add .toArray() at the end of the query:

const items = db.getCollection(xxx)
    .find({ ... })
    .toArray(); // The Magic (!)

for (var i = 0; i < items.length; i++) {
    console.log(items[i]);
}
Conserve answered 15/1, 2024 at 14:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.