Docs Menu

Docs HomeGo

Retrieve Data

On this page

  • Overview
  • Sample Data
  • Find Operations
  • Find All Documents
  • Find One Document
  • Modify Behavior
  • Aggregation Operations
  • Aggregation
  • Modify Behavior
  • Additional Information
  • API Documentation

In this guide, you can learn how to retrieve data from your MongoDB collections using read operations.

Read operations allow you to do the following:

  • Retrieve documents from your collections by using find operations

  • Perform transformations on documents in your collections by using aggregation operations

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", "Earl Grey"}, {"rating", 5}},
bson.D{{"type", "Masala"}, {"rating", 7}},
bson.D{{"type", "Earl Grey"}, {"rating", 9}},
}
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.

Use find operations to retrieve data from MongoDB. Find operations consist of the Find() and FindOne() methods.

The Find() method expects you to pass a Context type and a query filter. The method returns all documents that match the filter as a Cursor type.

To learn how to access data in a cursor, see Access Data From a Cursor.

The FindOne() method expects you to pass a Context type and a query filter. The method returns the first document that matches the filter as a SingleResult type.

To learn how to access data in a SingleResult see Unmarshalling.

You can modify the behavior of Find() and FindOne() by passing in a FindOptions and FindOneOptions type respectively. If you don't specify any options, the driver uses the default values for each option.

You can configure the commonly used options in both types with the following methods:

Method
Description
SetCollation()
The type of language collation to use when sorting results.
Default: nil
SetLimit()
The maximum number of documents to return.
Default: 0

Note

This option is not available for FindOneOptions. The FindOne() method internally uses SetLimit(-1).

SetProjection()
The fields to include in the returned documents.
Default: nil
SetSkip()
The number of documents to skip.
Default: 0
SetSort()
The field and type of sort to order the matched documents. You can specify an ascending or descending sort.
Default: none

The following example passes a context, filter, and FindOptions to the Find() method, which performs the following actions:

  • Matches documents where the rating falls between 5 and 10

  • Returns the type and rating, but excludes the _id

filter := bson.D{
{"$and",
bson.A{
bson.D{{"rating", bson.D{{"$gt", 5}}}},
bson.D{{"rating", bson.D{{"$lt", 10}}}},
}},
}
projection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
opts := options.Find().SetProjection(projection)
cursor, err := coll.Find(context.TODO(), filter, opts)
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)
}

The following example passes a context, filter, and FindOneOptions to the FindOne() method, which performs the following actions:

  • Matches all documents

  • A descending sort on the rating field

  • Returns the type and rating, but excludes the _id

filter := bson.D{}
sort := bson.D{{"rating", -1}}
projection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
opts := options.FindOne().SetSort(sort).SetProjection(projection)
var result bson.D
err := coll.FindOne(context.TODO(), filter, opts).Decode(&result)
if err != nil {
panic(err)
}
fmt.Println(result)

Use aggregation operations to retrieve and transform data from MongoDB. Perform aggregation operations using the Aggregate() method.

The Aggregate() method expects you to pass a Context type and an aggregation pipeline. An aggregation pipeline defines how to transform data through stages. Some of the stages are matching documents, renaming fields, and grouping values.

The method returns the resulting documents in a Cursor type. If you omit the $match stage, the pipeline proceeds using all documents in the collection.

To learn how to access data in a cursor, see Access Data From a Cursor.

The Aggregate() method optionally takes an AggregateOptions type, which represents options you can use to modify its behavior. If you don't specify any options, the driver uses the default values for each option.

The AggregateOptions type allows you to configure options with the following methods:

Method
Description
SetAllowDiskUse()
Whether to write to temporary files.
Default: false
SetBatchSize()
The number of documents to return in each batch.
Default: none
SetBypassDocumentValidation()
Whether to allow the write to opt-out of document level validation.
Default: false
SetCollation()
The type of language collation to use when sorting results.
Default: nil
SetMaxTime()
The maximum amount of time that the query can run on the server.
Default: nil
SetMaxAwaitTime()
The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
Default: nil
SetComment()
An arbitrary string to help trace the operation through the database profiler, currentOp and logs.
Default: ""
SetHint()
The index to use to scan for documents to retrieve.
Default: nil
SetLet()
Specifies parameters for the aggregate expression, which improves command readability by separating the variables from the query text.
Default: none

The following example passes a context and an aggregation pipeline that performs the following actions:

  • Groups reviews by types

  • Calculates the average rating of each type

groupStage := bson.D{
{"$group", bson.D{
{"_id", "$type"},
{"average", bson.D{
{"$avg", "$rating"},
}},
}}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{groupStage})
if err != nil {
panic(err)
}
var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("%v has an average rating of %v \n", result["_id"], result["average"])
}

To learn more about how to construct an aggregation pipeline, see the MongoDB server manual page on Aggregation.

For runnable examples of the find operations, see the following usage examples:

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:

←  Count DocumentsAccess Data From a Cursor →
Give Feedback
© 2022 MongoDB, Inc.

About

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