Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Java driver not obeying limit method

Tags:

java

mongodb

I have this query

DBCursor mongoCursor = mongoCollection.find(query).sort(sort).limit(5000);
long mongoCursorCount = mongoCursor.count();
myLogger.info("mongoCursorCount " + mongoCursorCount);

which is showing a mongoCursorCount value of 1.2M docs

The limit method works in shell queries but does it work via the mongo-java-driver-2.1.1.jar driver?

like image 288
kurt steele Avatar asked Oct 25 '25 21:10

kurt steele


1 Answers

By default MongoDB ignores limit and skip when they are applied together with count. To change this behavior you need to set applySkipLimit to true. See here for more details.

In Mongo shell this will ignore the limit and skip by default:

db.coll.find().limit(3).count();

And this will respect those modifiers:

db.coll.find().limit(3).count(true);

It could be possible that you are using an older version of Mongo shell where this is not default or something like that.

To fix your Java code use size() instead of count() - that's like calling count(true) instead of count() in shell.

like image 135
yǝsʞǝla Avatar answered Oct 28 '25 11:10

yǝsʞǝla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!