longda
longda

Reputation: 10423

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?

Upvotes: 4

Views: 5573

Answers (2)

Thilo
Thilo

Reputation: 262584

According to the JavaDoc you linked to the second int parameter is not the maximum number to return, but

batchSize - if positive, is the # of objects per batch sent back from the db. all objects that match will be returned. if batchSize < 0, its a hard limit, and only 1 batch will either batchSize or the # that fit in a batch

Maybe a negative number (-20) would do what you want, but I find the statement above too confusing to be sure about it, so I would set the batchSize to 20 and then filter in your application code.

Maybe file this as a bug / feature request. There should be a way to specify skip/limit that works just like on the shell interface. (Update: and there is, on the cursor class, see the other answer).

Upvotes: 3

Alexander Azarov
Alexander Azarov

Reputation: 13221

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

So you simply need to do

def shape_cursor = mongo.shapes.find(...).limit(20);

Upvotes: 6

Related Questions