I am trying to use a cursor to iterate over documents, i want to store them in a list,and later on return a list of type DBOject.
Here is what I am trying:
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;
}
I don't know how to convert the data type into a primitive one form the cursor. I tried searching,but no clues.
Please help.
Thanks
DBCursor(DBCollection collection, DBObject query, DBObject fields, ReadPreference readPreference) Initializes a new database cursor.
BasicDBObject(java.util.Map map) Creates an object from a map. BasicDBObject(java.lang.String key, java.lang.Object value) Creates an object with the given key/value.
Sets the maximum number of documents or index keys to scan when executing the query. FindIterable<TResult> maxTime(long maxTime, java.util.concurrent.TimeUnit timeUnit) Sets the maximum execution time on the server for this operation.
Class BasicDBListAn implementation of List that reflects the way BSON lists work. See Also: Serialized Form.
@sdanzig solution will work but... If you like to type less code you can do this:
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;
}
the DBCursor.toArray() method of DBCursor returns a List
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With