eclipse - cursor.next() always returns "java.util.NoSuchElementException" -


i writing program in java reads query results mongodb.

below code (which gives exception):

if(output != null){                 basicdbobject wherequery = new basicdbobject();                 dbcursor cursor = null;                 (dbobject obj : output.results()) {                     string userid = obj.get("userid").tostring();                     wherequery.put("user_id", userid);                                                                                    cursor = users.find(wherequery);                     system.out.println(cursor.tostring());                     system.out.println("this user name tweeted "+ cursor.next());                   }             } 

when run code, first value of cursor gets printed using sysout statement in last line, second value comes 'for' loop results in exception. wonder why?

the sysout statement before cursor.next() prints current value in cursor time, placed there verify whether cursor has value.

i have tried hasnext() while loop cursor.next(), enters loop first time rest of checks jumps out.

error stack trace:    exception in thread "main" java.util.nosuchelementexception    @ com.mongodb.queryresultiterator.next(queryresultiterator.java:111)    @ com.mongodb.dbcursor._next(dbcursor.java:510)    @ com.mongodb.dbcursor.next(dbcursor.java:581)    @ readdata.referenceddatamodel(readdata.java:97)    @ readdata.main(readdata.java:131) 

i'm not sure answer, it's worth try:

string userid = obj.get("userid").tostring(); cursor = users.find(wherequery); if(cursor.hasnext()) {     // object object, json document     basicdbobject obj = cursor.next();       // print obj console json file     system.out.println(obj);      // can property obj.get...(); method such .getstring()     // below code extract user_id object received via find query      string id = obj.getstring("user_id"); } 

if sure result have 1 document can use code:

basicdbobject obj = users.findone(wherequery); 

very useful resource java , mongo:

http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -