diff --git a/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java b/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java index abdbc328a1..4ef5c2907e 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java @@ -390,7 +390,12 @@ private BsonDocument getCommand(final OperationContext operationContext, final i if (batchSize < 0 && Math.abs(batchSize) < limit) { commandDocument.put("limit", new BsonInt32(Math.abs(batchSize))); } else if (batchSize != 0) { - commandDocument.put("batchSize", new BsonInt32(Math.abs(batchSize))); + int effectiveBatchSize = Math.abs(batchSize); + if (effectiveBatchSize == limit) { + // avoid an open cursor on server side when batchSize and limit are equal + effectiveBatchSize++; + } + commandDocument.put("batchSize", new BsonInt32(effectiveBatchSize)); } } if (limit < 0 || batchSize < 0) { diff --git a/driver-core/src/test/resources/unified-test-format/crud/find.json b/driver-core/src/test/resources/unified-test-format/crud/find.json index 6bf1e4e445..325cd96c21 100644 --- a/driver-core/src/test/resources/unified-test-format/crud/find.json +++ b/driver-core/src/test/resources/unified-test-format/crud/find.json @@ -237,6 +237,68 @@ ] } ] + }, + { + "description": "Find with batchSize equal to limit", + "operations": [ + { + "object": "collection0", + "name": "find", + "arguments": { + "filter": { + "_id": { + "$gt": 1 + } + }, + "sort": { + "_id": 1 + }, + "limit": 4, + "batchSize": 4 + }, + "expectResult": [ + { + "_id": 2, + "x": 22 + }, + { + "_id": 3, + "x": 33 + }, + { + "_id": 4, + "x": 44 + }, + { + "_id": 5, + "x": 55 + } + ] + } + ], + "expectEvents": [ + { + "client": "client0", + "events": [ + { + "commandStartedEvent": { + "command": { + "find": "coll0", + "filter": { + "_id": { + "$gt": 1 + } + }, + "limit": 4, + "batchSize": 5 + }, + "commandName": "find", + "databaseName": "find-tests" + } + } + ] + } + ] } ] }