2

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();
2
  • 1) while is preferred. 2) save cursor length in variable and try for loop 3) initialize b again with cursor.length(0-1 after re-initialization cursor to people.find() Commented Oct 1, 2015 at 17:46
  • 1
    As a general note, your condition a < b is wrong, should be a < b + 1 or a <= b. There are n elements satisfying 0 <= x && x < n and this is usually what a for looks like Commented Oct 1, 2015 at 17:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.