Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit the number of results when using the Java driver for mongo db?

http://api.mongodb.org/java/2.1/com/mongodb/DBCollection.html#find(com.mongodb.DBObject,com.mongodb.DBObject,int,int)

Using this with Grails and the mongo db plugin.

Here's the code I'm using... not sure why but the cursor is returning the entire set of data. In this case, I'm just trying to return the first 20 matches (with is_processed = false):

def limit = {
    def count = 1;
    def shape_cursor = mongo.shapes.find(new BasicDBObject("is_processed", false),new BasicDBObject(),0,20);
    while(shape_cursor.hasNext()){
        shape_cursor.next();
        render "<div>" + count + "</div"
        count++;
    }
}

Anyone have an idea?

like image 243
longda Avatar asked Jan 21 '23 12:01

longda


1 Answers

limit is a method of DBCursor: DBCursor.limit(n).

So you simply need to do

def shape_cursor = mongo.shapes.find(...).limit(20);
like image 144
Alexander Azarov Avatar answered Jan 28 '23 18:01

Alexander Azarov