9

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

3 Answers 3

16

@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

Sign up to request clarification or add additional context in comments.

3 Comments

Warning: Calling toArray or length on a DBCursor will irrevocably turn it into an array. This means that, if the cursor was iterating over ten million results (which it was lazily fetching from the database), suddenly there will be a ten-million element array in memory. Before converting to an array, make sure that there are a reasonable number of results using skip() and limit(). For example, to get an array of the 1000-1100th elements of a cursor, use List obj = collection.find( query ).skip( 1000 ).limit( 100 ).toArray(); api.mongodb.org/java/2.0/com/mongodb/DBCursor.html
Of cause toArray method can be a problem with large results, but that's what the question was asking - how to turn cursor to a list.
I don't disagree with the answer, I think it is correct, I just added a warning for a case when cursor has huge number of results in it.
6

For what you're trying to do, no need to read the individual fields. You do have to initialize your list. Plus, you were calling next() twice, once in the print statement. You can just use the return value of next() rather than calling curr(). Oh, and someone rightly suggested you should pass in the "limit" argument rather than use 10, unless that was intentional:

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;
}

4 Comments

@sdanzig Can you please explain why should we close the cursor? Does no closing the cursor have any drawback?
@PratikPatel Cursors consume resources, so closing them keeps things tidy. Cursors get closed when they're exhausted (fully iterated through), but if only partially iterated through, explicitly closing them helps avoid waiting for the 10 minute timeout to free the resources.
@sdanzig Is what you said documented in Mongo Doc? I can not find it, can you give me the URL, thx.
@PratikPatel Going by what I read here: stackoverflow.com/questions/24260677/… ... ask Neil Lunn :)
1

In my case I'm working with Documents:

List<Document> employees = (List<Document>) collection.find().into(
                new ArrayList<Document>());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.