开发者

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.开发者_StackOverflowfind(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?


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

So you simply need to do

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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜