kurt steele
kurt steele

Reputation: 157

Mongo Java driver not obeying limit method

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?

Upvotes: 4

Views: 827

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

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.

Upvotes: 6

Related Questions