Java 无法检索mongodb中的文档列表
为了检索投票列表Java 无法检索mongodb中的文档列表,java,json,spring,mongodb,Java,Json,Spring,Mongodb,为了检索投票列表 { "question":"what is your color?", "choices":[{"option":"yello"},{"option":"blue"}], "creation-date":"2014-04-13", "expiry date":"2014-04-14" } public List getPolls() { 试一试{ mongoClient=新的mongoClient(“NavDeep”,27017); db=mo
{
"question":"what is your color?",
"choices":[{"option":"yello"},{"option":"blue"}],
"creation-date":"2014-04-13",
"expiry date":"2014-04-14"
}
public List getPolls()
{
试一试{
mongoClient=新的mongoClient(“NavDeep”,27017);
db=mongoClient.getDB(“短信投票”);
collection=db.getCollection(“pollsCollection”);
}捕获(例外e){
e、 printStackTrace();
}
列表轮询=新建ArrayList();
DBCursor=collection.find();
while(cursor.hasNext())
{
DBObject object=cursor.next();
为了检索列表,我应该写些什么????
}
}
mongoClient.close();
回访民调;
}
但我在BasicDBList pollList=(BasicDBList)object.get(“pollsCollection”)附近遇到空指针异常;
有人能帮我吗?我应该在get()里面写些什么
Thnks,
deepthi我认为问题可能是您在上面的行中执行了两次cursor.next(),一次拉两条记录 如果您尝试:
public List<Poll> getPolls()
{
try {
mongoClient=new MongoClient("NavDeep",27017);
db=mongoClient.getDB("sms-voting");
collection=db.getCollection("pollsCollection");
} catch(Exception e){
e.printStackTrace();
}
List<Poll> polls = new ArrayList<Poll>();
DBCursor cursor=collection.find();
while(cursor.hasNext())
{
DBObject object = cursor.next();
what should i write in order to retrieve List<Poll>????
}
}
mongoClient.close();
return polls;
}
而不是
polls.add(object)
与迭代光标不同,您似乎希望使用该方法:
DBCursor cursor=collection.find();
List=cursor.toArray();
一般来说,游标是个好主意,您可能应该在该循环中构建任何数组类型的结果。但这是一种更改光标的方法。哦,对不起,while循环中没有光标。next()是我的输入错误。请忽略它。但我无法执行polls.add(cursor.next()),因为cursor.next返回dbobject,polls是一个名为Poll的java对象列表。如果您在此处修复代码中的输入错误,以便我们可以尝试对其进行诊断,可能会有所帮助。如果不在while循环中调用cursor.next(),那么对象是如何分配的?“object”在您的示例中是集合中的单个“first”文档。您在迭代游标时得到了这个结果,因此尝试从中调用“集合”是无效的。你到底想做什么?将集合中找到的所有文档作为列表返回?是..我想将所有文档作为列表检索
polls.add(cursor.next())
DBCursor cursor = collection.find();
List<DBObject> list = cursor.toArray();