Retrieve Data
On this page
Overview
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
Sample Data
The examples in this section use the following Review
struct as a model for documents
in the reviews
collection:
type Review struct { Item string `bson:"item,omitempty"` Rating int32 `bson:"rating,omitempty"` DateOrdered time.Time `bson:"date_ordered,omitempty"` }
To run the examples in this guide, load these documents into the
tea.reviews
collection with the following
snippet:
coll := client.Database("tea").Collection("reviews") docs := []interface{}{ Review{Item: "Masala", Rating: 10, DateOrdered: time.Date(2009, 11, 17, 0, 0, 0, 0, time.Local)}, Review{Item: "Sencha", Rating: 7, DateOrdered: time.Date(2009, 11, 18, 0, 0, 0, 0, time.Local)}, Review{Item: "Masala", Rating: 9, DateOrdered: time.Date(2009, 11, 12, 0, 0, 0, 0, time.Local)}, Review{Item: "Masala", Rating: 8, DateOrdered: time.Date(2009, 12, 1, 0, 0, 0, 0, time.Local)}, Review{Item: "Sencha", Rating: 10, DateOrdered: time.Date(2009, 12, 17, 0, 0, 0, 0, time.Local)}, Review{Item: "Hibiscus", Rating: 4, DateOrdered: time.Date(2009, 12, 18, 0, 0, 0, 0, time.Local)}, } result, err := coll.InsertMany(context.TODO(), docs)
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 describes the tea variety a customer ordered, their
rating, and the date of the order. These descriptions correspond to the
item
, rating
, and date_ordered
fields.
Find Operations
Use find operations to retrieve data from MongoDB. Find operations
consist of the Find()
and FindOne()
methods.
Find All Documents
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.
For an example that uses the Find()
method, see the Find Example
section of this page. To learn how to access data by using a cursor, see
the Access Data From a Cursor guide.
Find One Document
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.
For an example that uses the FindOne()
method, see the
Find One Example section of this page. For an example that
uses FindOne()
and queries by using a specific ObjectId
value, see
the Find One by ObjectId Example section of this page.
To learn how to access data from a SingleResult
type, see
Unmarshalling in the BSON guide.
Modify Behavior
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 NoteThis option is not available for |
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 |
Find Example
The following example passes a context, filter, and FindOptions
to
the Find()
method, which performs the following actions:
Matches documents where the
rating
value is between5
and9
(exclusive)Sorts matched documents in ascending order by
date_ordered
filter := bson.D{ {"$and", bson.A{ bson.D{{"rating", bson.D{{"$gt", 5}}}}, bson.D{{"rating", bson.D{{"$lt", 9}}}}, }}, } sort := bson.D{{"date_ordered", 1}} opts := options.Find().SetSort(sort) // Retrieves documents that match the filter and prints them as structs cursor, err := coll.Find(context.TODO(), filter, opts) if err != nil { panic(err) } var results []Review if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { res, _ := json.Marshal(result) fmt.Println(string(res)) }
Find One Example
The following example passes a context, filter, and FindOneOptions
to the FindOne()
method, which performs the following actions:
Matches documents where the
date_ordered
value is on or before November 30, 2009Skips the first two matched documents
filter := bson.D{{"date_ordered", bson.D{{"$lte", time.Date(2009, 11, 30, 0, 0, 0, 0, time.Local)}}}} opts := options.FindOne().SetSkip(2) // Retrieves a document that matches the filter and prints it as // a struct var result Review err := coll.FindOne(context.TODO(), filter, opts).Decode(&result) if err != nil { panic(err) } res, _ := json.Marshal(result) fmt.Println(string(res))
Find One by ObjectId Example
This example defines an id
variable with a value of type ObjectId
and uses id
to specify a query filter. The filter matches a document
with an _id
field value that corresponds to the id
variable.
This example queries for the following document based on its _id
value:
{ _id: ObjectId('65170b42b99efdd0b07d42de'), item: "Hibiscus", rating : 4, date_ordered : 2009-12-18T05:00:00.000+00:00 }
The following code passes the filter and a FindOneOptions
instance
as parameters to the FindOne()
method to perform the following actions:
Match the document with the specified
ObjectId
valueProject only the
Item
andRating
fields of the matched document
id, err := primitive.ObjectIDFromHex("65170b42b99efdd0b07d42de") if err != nil { panic(err) } // Creates a filter to match a document that has the specified // "_id" value filter := bson.D{{"_id", id}} opts := options.FindOne().SetProjection(bson.D{{"item", 1}, {"rating", 1}}) // Retrieves a document that matches the filter and prints it as // a struct var result Review err = coll.FindOne(context.TODO(), filter, opts).Decode(&result) if err != nil { panic(err) } res, _ := bson.MarshalExtJSON(result, false, false) fmt.Println(string(res))
Note
The Go driver automatically generates a unique ObjectId
value for each document's _id
field, so your ObjectId
value
might differ from the preceding code example. For more information
about the _id
field, see the _id Field
section of the Insert a Document page.
Aggregation Operations
Use aggregation operations to retrieve and transform data from
MongoDB. Perform aggregation operations using the Aggregate()
method.
Aggregation
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.
Modify Behavior
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 |
Example
The following example passes a context and an aggregation pipeline that performs the following actions:
Groups reviews by item ordered
Calculates the average rating for each item
groupStage := bson.D{ {"$group", bson.D{ {"_id", "$item"}, {"average", bson.D{ {"$avg", "$rating"}, }}, }}} cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{groupStage}) if err != nil { panic(err) } // Prints the average "rating" for each item var results []bson.M if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Printf("%v had 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.
Additional Information
For runnable examples of the find operations, see the following usage examples:
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: