How to 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 returns the entire data set. 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++; } } 

Does anyone have an idea?

+4
source share
2 answers

limit is the DBCursor method: DBCursor.limit (n) .

So you just need to do

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

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

batchSize - if positive, - the number of objects for each batch sent back from db. All returned items will be returned. if batchSize <0, its hard limit and only 1 batch will be either batchSize or #, which correspond to the package

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

Perhaps this is a file as an error / function request. There should be a way to specify skip / limit, which works the same way as on the shell interface. (Update: and there is another answer in the cursor class).

+3
source

All Articles