Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list from DbCursor in MongoDB and Java

Tags:

java

mongodb

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

like image 837
ApJo Avatar asked Oct 25 '13 03:10

ApJo


People also ask

What is DBCursor in Mongodb?

DBCursor​(DBCollection collection, DBObject query, DBObject fields, ReadPreference readPreference) Initializes a new database cursor.

What is BasicDBObject in Java?

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.

What is FindIterable in Java?

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.

What is BasicDBList?

Class BasicDBListAn implementation of List that reflects the way BSON lists work. See Also: Serialized Form.


1 Answers

@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

like image 181
Dmitri Avatar answered Sep 22 '22 14:09

Dmitri