Limit the Number of Returned Results
Overview
In this guide, you can learn how to limit the number of documents returned from a read operation.
Sample Data
To run the examples in this guide, load these documents into the
tea.ratings
collection with the following
snippet:
coll := client.Database("tea").Collection("ratings") docs := []interface{}{ bson.D{{"type", "Masala"}, {"rating", 10}}, bson.D{{"type", "Assam"}, {"rating", 5}}, bson.D{{"type", "Oolong"}, {"rating", 7}}, bson.D{{"type", "Earl Grey"}, {"rating", 8}}, bson.D{{"type", "English Breakfast"}, {"rating", 5}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
Non-existent Databases and Collections
If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.
Each document contains a rating for a type of tea that corresponds to
the type
and rating
fields.
Note
Each example truncates the ObjectID
value because the driver
generates them uniquely.
Limit
To limit the number of documents returned from a query, pass the
number of documents you want returned to the SetLimit()
method of
the read operation's options.
Specify the options as the last parameter to the following read operation methods:
Find()
CountDocuments()
gridfs.Bucket.Find()
If the limit is 0
or exceeds the number of matched
documents, the method returns all the documents. If the limit is a
negative number, the method behaves as if the limit was the absolute
value of the negative number and closes the cursor after retrieving
documents.
Example
The following example shows how to return two documents:
filter := bson.D{} opts := options.Find().SetLimit(2) cursor, err := coll.Find(context.TODO(), filter, opts) var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
Multiple Options
If you configure other options alongside the SetLimit()
method,
the driver performs the limit last regardless of the order you list
the options.
Example
The following example performs the following actions in order using the
Find()
method:
Sort the
rating
field in descending orderSkip the first document
Return the first two of the remaining documents
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"rating", -1}}).SetLimit(2).SetSkip(1) cursor, err := coll.Find(context.TODO(), filter, opts) var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
Tip
Using any of the following option declarations also produce the same result:
multiOptions := options.Find().SetSort(bson.D{{"rating", -1}}).SetSkip(1).SetLimit(2) multiOptions := options.Find().SetLimit(2).SetSort(bson.D{{"rating", -1}}).SetSkip(1) multiOptions := options.Find().SetLimit(2).SetSkip(1).SetSort(bson.D{{"rating", -1}}) multiOptions := options.Find().SetSkip(1).SetSort(bson.D{{"rating", -1}}).SetLimit(2) multiOptions := options.Find().SetSkip(1).SetLimit(2).SetSort(bson.D{{"rating", -1}})
Aggregation
You can also include the $limit stage to specify a limit in an aggregation pipeline.
Example
The following example shows how to return three documents:
limitStage := bson.D{{"$limit", 3}} cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{limitStage}) if err != nil { panic(err) } var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
Additional Information
To learn more about the operations mentioned, see the following guides:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: