Skip to content

Commit 79bf126

Browse files
author
Divjot Arora
committed
Support negative limits for find commands
GODRIVER-867 Change-Id: Ibaad9e1a081969499a91ca426f38c54bede7fad7
1 parent 69aa7c5 commit 79bf126

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

mongo/collection_internal_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1747,6 +1747,21 @@ func TestCollection_Find_Error(t *testing.T) {
17471747
})
17481748
}
17491749

1750+
func TestCollection_Find_NegativeLimit(t *testing.T) {
1751+
coll := createTestCollection(t, nil, nil)
1752+
initCollection(t, coll)
1753+
1754+
c, err := coll.Find(ctx, bson.D{}, options.Find().SetLimit(-2))
1755+
require.NoError(t, err)
1756+
require.Equal(t, int64(0), c.ID()) // single batch returned so cursor should not have valid ID
1757+
1758+
var numDocs int
1759+
for c.Next(ctx) {
1760+
numDocs++
1761+
}
1762+
require.Equal(t, 2, numDocs)
1763+
}
1764+
17501765
func TestCollection_FindOne_found(t *testing.T) {
17511766
if testing.Short() {
17521767
t.Skip("skipping integration test in short mode")

x/mongo/driver/find.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,13 @@ func Find(
113113
cmd.Opts = append(cmd.Opts, hintElem)
114114
}
115115
if fo.Limit != nil {
116-
cmd.Opts = append(cmd.Opts, bsonx.Elem{"limit", bsonx.Int64(*fo.Limit)})
116+
limit := *fo.Limit
117+
if limit < 0 {
118+
cmd.Opts = append(cmd.Opts, bsonx.Elem{"singleBatch", bsonx.Boolean(true)})
119+
limit = -1 * limit
120+
}
121+
122+
cmd.Opts = append(cmd.Opts, bsonx.Elem{"limit", bsonx.Int64(limit)})
117123
}
118124
if fo.Max != nil {
119125
maxElem, err := interfaceToElement("max", fo.Max, registry)

0 commit comments

Comments
 (0)