我试图使用游标迭代文档,我想将它们存储在列表中,然后返回类型DBOject的列表.
这是我正在尝试的:
public List<DBObject> getResultsInDescendingOrderByDate(int limit) {
List<DBObject> myList = null;
DBCursor myCursor=myCollection.find().sort(new BasicDBObject("date",-1)).limit(10);
try {
while(myCursor.hasNext()) {
System.out.print(myCursor.next());
myList.add(new BasicDBObject("_id",(String) myCursor.curr().get("_id"))
.append("title",(String) myCursor.curr().get("title"))
.append("author",(String) myCursor.curr().get("author"))
.append("permalink",(String) myCursor.curr().get("permalink"))
.append("body",(String) myCursor.curr().get("body"))
.append("comment",new BasicDBObject("comments",(String) myCursor.curr().get("comments")))
.append("tags",new BasicDBObject("tags",(String) myCursor.curr().get("tags"))
.append("date",(Date) myCursor.curr().get("date"))));
myCursor.next();
}
}
finally {
myCursor.close();
}
return myList;
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何将数据类型转换为光标中的原始数据类型.我试着搜索,但没有线索.
请帮忙.
谢谢
Dmi*_*tri 15
@sdanzig解决方案可以工作但是...如果你想输入更少的代码,你可以这样做:
public List<DBObject> getResultsInDescendingOrderByDate(int limit) {
List<DBObject> myList = null;
DBCursor myCursor=myCollection.find().sort(new BasicDBObject("date",-1)).limit(10);
myList = myCursor.toArray();
return myList;
}
Run Code Online (Sandbox Code Playgroud)
所述DBCursor.toArray() DBCursor的方法返回一个列表
对于您要做的事情,无需阅读各个字段.您必须初始化列表.另外,你在print语句中调用了next()两次.你可以使用next()的返回值而不是调用curr().哦,有人正确地建议你应该传递"限制"参数而不是使用10,除非这是故意的:
public List<DBObject> getResultsInDescendingOrderByDate(int limit) {
List<DBObject> myList = new ArrayList<DBObject>();
DBCursor myCursor=myCollection.find().sort(new BasicDBObject("date",-1)).limit(limit);
try {
while(myCursor.hasNext()) {
myList.add(myCursor.next());
}
}
finally {
myCursor.close();
}
return myList;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19904 次 |
| 最近记录: |