-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathproject.txt
237 lines (175 loc) · 6.55 KB
/
project.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
.. _golang-project:
==============================
Specify Which Fields to Return
==============================
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: read, code example, pipeline stage, customize output
:description: Learn how to specify which fields to return in MongoDB documents using projections in Go, including examples for including or excluding fields.
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to specify which fields to return in a
document.
Sample Data
~~~~~~~~~~~
The examples in this guide use the following ``Course`` struct as a model for documents
in the ``courses`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/projection.go
:start-after: start-course-struct
:end-before: end-course-struct
:language: go
:dedent:
The ``omitempty`` :ref:`struct tag<golang-struct-tags>` 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:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/projection.go
:language: go
:dedent:
:start-after: begin insertDocs
:end-before: end insertDocs
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
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.
Projection
----------
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.
Exclude a Field
~~~~~~~~~~~~~~~
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.
Example
```````
The following example excludes the ``course_id`` and ``enrollment``
fields from the matched documents returned by the ``Find()`` method:
.. io-code-block::
:copyable: true
.. input::
:language: go
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))
}
.. output::
:language: none
:visible: false
{"title":"Primate Behavior"}
{"title":"Revolution and Reform"}
Include a Field
~~~~~~~~~~~~~~~
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.
.. _golang-include-projection:
Example
```````
The following example includes only the ``title`` and ``enrollment`` fields
from the matched documents returned by the ``Find()`` method:
.. io-code-block::
:copyable: true
.. input::
:language: go
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))
}
.. output::
:language: none
:visible: false
{"title":"Primate Behavior","enrollment":40}
{"title":"Revolution and Reform","enrollment":12}
Aggregation
~~~~~~~~~~~
You can also create a :manual:`$project </reference/operator/aggregation/project/>`
stage to specify a projection in an aggregation pipeline.
Example
```````
The following example includes only the ``title`` and ``course_id`` fields
from the matched documents returned by the ``Aggregate()`` method:
.. io-code-block::
:copyable: true
.. input::
:language: go
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))
}
.. output::
:language: none
:visible: false
{"title":"Primate Behavior","course_id":"PSY2030"}
{"title":"Revolution and Reform","course_id":"HIST3080"}
Additional Information
----------------------
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-retrieve`
- :ref:`golang-compound-operations`
- :ref:`golang-aggregation`
To learn about projecting text scores from your text search, see :ref:`golang-search-text`.
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `Find() <{+api+}/mongo#Collection.Find>`__
- `FindOptionsBuilder.SetProjection() <{+api+}/mongo/options#FindOptionsBuilder.SetProjection>`__
- `FindOne() <{+api+}/mongo#Collection.FindOne>`__
- `FindOneAndDelete() <{+api+}/mongo#Collection.FindOneAndDelete>`__
- `FindOneAndReplace() <{+api+}/mongo#Collection.FindOneAndReplace>`__
- `FindOneAndUpdate() <{+api+}/mongo#Collection.FindOneAndUpdate>`__
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__