我正在用java编写一个程序来读取MongoDB的查询结果。
下面是代码(给出例外):
if(output != null){
BasicDBObject whereQuery = new BasicDBObject();
DBCursor cursor = null;
for (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 who tweeted "+ cursor.next());
}
}
当我运行此代码时,只使用最后一行中的sysout语句打印游标的第一个值,第二个值来自' for'循环导致异常。不知道为什么?
在cursor.next()之前的sysout语句一直打印游标中的当前值,将其放在那里以验证游标是否实际具有值。
我已经为cursor.next()尝试了hasNext()while循环,它只是第一次进入循环,其余的检查只是跳出来。
Error stack trace:
Exception in thread "main" java.util.NoSuchElementException
at com.mongodb.QueryResultIterator.next(QueryResultIterator.java:111)
at com.mongodb.DBCursor._next(DBCursor.java:510)
at com.mongodb.DBCursor.next(DBCursor.java:581)
at ReadData.referencedDataModel(ReadData.java:97)
at ReadData.main(ReadData.java:131)
答案 0 :(得分:3)
我不确定你的答案,但值得一试:
String UserID = obj.get("UserID").toString();
cursor = users.find(whereQuery);
if(cursor.hasNext()) {
// the object will be your object, its basically a json document
BasicDBObject obj = cursor.next();
// print obj to console as json file
System.out.println(obj);
// you can get any property with obj.get...(); method such as .getString()
// The below code will extract the User_ID from the object you received via find query
string id = obj.getString("User_ID");
}
如果您确定结果只有一个文档,则可以使用此代码:
BasicDBObject obj = users.findOne(whereQuery);
关于java和Mongo非常有用的资源:
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
答案 1 :(得分:1)
if(output != null){
BasicDBObject whereQuery = new BasicDBObject();
DBCursor cursor;
for (DBObject obj : output.results()) {
String UserID = obj.get("UserID").toString();
System.out.println("The real results "+ UserID);
whereQuery.put("User_ID", UserID);
DBObject value = users.findOne(whereQuery);
if(value != null)
System.out.println("The user who used the word in the tweet: " +value.get("User_Name").toString());
else
System.out.println("The user profile is not available");
}
}
螺丝游标!
谢谢@Disposer!