Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversGo Driver

Specify Which Fields to Return

On this page

  • Overview
  • Sample Data
  • Projection
  • Exclude a Field
  • Include a Field
  • Aggregation
  • Additional Information
  • API Documentation

In this guide, you can learn how to specify which fields to return in a document.

The examples in this guide use the following Course struct as a model for documents in the courses collection:

type Course struct {
Title string `bson:"title,omitempty"`
CourseId string `bson:"course_id,omitempty"`
Enrollment int32 `bson:"enrollment,omitempty"`
}

The omitempty struct tag directs the driver to exclude fields when unmarshalling based on your projection specification.

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: "Primate Behavior", CourseId: "PSY2030", Enrollment: 40},
Course{Title: "Revolution and Reform", CourseId: "HIST3080", Enrollment: 12},
}
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, course ID, and maximum enrollment, corresponding to the title, course_id, and enrollment fields in each document.

A projection specifies which fields to return in matched documents. The projection document contains field names with a 1 to include the corresponding field or 0 to exclude it. If you are using an aggregation framework, you can also specify a projection to include newly computed fields.

You can specify a projection by passing a projection document to the SetProjection() method. The following operations take an options object as a parameter:

  • Find()

  • FindOne()

  • FindOneAndDelete()

  • FindOneAndReplace()

  • FindOneAndUpdate()

Tip

If you don't specify a projection, the operation returns all the fields in matched documents.

To exclude a field, pass the field you want to exclude with a 0 to the SetProjection() method. The driver includes all fields that are not explicitly excluded in the projection document, if you specify any fields to exclude.

The following example excludes the course_id and enrollment fields from the matched documents returned by the Find() method:

filter := bson.D{}
opts := options.Find().SetProjection(bson.D{{"course_id", 0}, {"enrollment", 0}})
cursor, err := coll.Find(context.TODO(), filter, opts)
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))
}

To include a field, pass the field you want to include with a 1 to the SetProjection() method. The driver excludes all fields that are not explicitly included in the projection document, if you specify any fields to include.

The following example includes only the title and enrollment fields from the matched documents returned by the Find() method:

filter := bson.D{}
opts := options.Find().SetProjection(bson.D{{"title", 1}, {"enrollment", 1}})
cursor, err := coll.Find(context.TODO(), filter, opts)
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))
}

You can also create a $project stage to specify a projection in an aggregation pipeline.

The following example includes only the title and course_id fields from the matched documents returned by the Aggregate() method:

projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"course_id", 1}}}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{projectStage})
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))
}

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

To learn about projecting text scores from your text search, see Search Text.

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

←  Limit the Number of Returned ResultsSearch Text →