Search code examples
javamongodbcursor

Cursor functionality in a for loop as opposed to a while loop?


I am printing documents in a MongoDB database with a DBCursor. When I use the while loop, it works fine.

        DBCursor cursor = people.find(new BasicDBObject("isPerson",true));
        while(cursor.hasNext()){
            System.out.println(cursor.next());
        }
        cursor.close();

With a while loop, the documents are printed. When I use a for loop, I get an error.

        cursor = people.find(new BasicDBObject("isPerson",true));
        for(int a=0;a<cursor.length()-1;a++){                       
            System.out.println(cursor.next());                
        }
        cursor.close();

This is the error:

java.lang.IllegalArgumentException: Can't switch cursor access methods
at com.mongodb.DBCursor.checkIteratorOrArray(DBCursor.java:841)
at com.mongodb.DBCursor.next(DBCursor.java:168)
at mongotest.MongoTest.main(MongoTest.java:39)

But even when I get around the error with the following code, nothing is printed.

        cursor = people.find(new BasicDBObject("isPerson",true));
        int b = cursor.length()-1;
        cursor = people.find(new BasicDBObject("isPerson",true));
        for(int a=0;a<b;a++){                       
            System.out.println(cursor.next());                
        }
        cursor.close();

Solution

  • Look at next() method inside DBCursor class

    @Override
    
    public DBObject next() {
        checkIteratorOrArray(IteratorOrArray.ITERATOR);
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
    
        return nextInternal();
    }
    

    it clearly mentioned if !hasNext() throw an exception

    In Addition

    If you keep cursor.length() in for loop and keep on iterate by calling cursor.next() , cursor length keep on change and throw an exception.

    Look at your alternate way, you have initialize the variable i with cursor length and value of i does not change during execution of FOR loop.