Docs Menu

Limit the Number of Returned Results

On this page

  • Overview
  • Limit
  • Multiple Options
  • Aggregation
  • Additional Information

In this guide, you can learn how to limit the number of documents returned from a read operation.

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

The server implicitly creates the necessary database and collection when you perform a write operation against them if they don't already exist.

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.

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.

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)
}

If you configure other options alongside the SetLimit() method, the driver performs the limit last regardless of the order you list the options.

The following example performs the following actions in order using the Find() method:

  • Sort the rating field in descending order
  • Skip 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}})

You can also include the $limit stage to specify a limit in an aggregation pipeline.

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)
}

To learn more about the operations mentioned, see the following guides:

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

←  Skip Returned ResultsSpecify Which Fields to Return →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.