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
The examples in this guide use the following Course
struct as a model for documents
in the courses
collection:
type Course struct { Title string Enrollment int32 }
To run the examples in this guide, load the sample data into the
db.courses
collection with the following snippet:
coll := client.Database("db").Collection("courses") docs := []interface{}{ Course{Title: "Romantic Era Music", Enrollment: 15}, Course{Title: "Concepts in Topology", Enrollment: 35}, Course{Title: "Ancient Greece", Enrollment: 100}, Course{Title: "Physiology I", Enrollment: 60}, } result, err := coll.InsertMany(context.TODO(), docs)
Tip
Nonexistent 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 description of a university course that
includes the course title and maximum enrollment, corresponding to
the title
and enrollment
fields in each document.
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.
The following read operations take an options object as a parameter:
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 uses the absolute value of the negative
number as the limit and closes the cursor after retrieving
documents.
Example
The following example shows how to return two documents that have an
enrollment
field value greater than 20:
filter := bson.D{{"enrollment", bson.D{{"$gt", 20}}}} opts := options.Find().SetLimit(2) cursor, err := coll.Find(context.TODO(), filter, opts) var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
{"title":"Concepts in Topology","enrollment":35} {"title":"Ancient Greece","enrollment":100}
Multiple Options
The driver performs the limit behavior last regardless of the order in which you set any other options.
Example
The following example performs a Find()
operation with the following behavior:
Sorts the results in descending order on the
enrollment
fieldSkips the first document
Returns the first two of the remaining documents
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"enrollment", -1}}).SetLimit(2).SetSkip(1) cursor, err := coll.Find(context.TODO(), filter, opts) var results []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
{"title":"Physiology I","enrollment":60} {"title":"Concepts in Topology","enrollment":35}
Tip
Using any of the following option configurations also produces the same result:
opts := options.Find().SetSort(bson.D{{"enrollment", -1}}).SetSkip(1).SetLimit(2) opts := options.Find().SetLimit(2).SetSort(bson.D{{"enrollment", -1}}).SetSkip(1) opts := options.Find().SetLimit(2).SetSkip(1).SetSort(bson.D{{"enrollment", -1}}) opts := options.Find().SetSkip(1).SetSort(bson.D{{"enrollment", -1}}).SetLimit(2) opts := options.Find().SetSkip(1).SetLimit(2).SetSort(bson.D{{"enrollment", -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 []Course if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res)) }
{"title":"Romantic Era Music","enrollment":15} {"title":"Concepts in Topology","enrollment":35} {"title":"Ancient Greece","enrollment":100}
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: