Skip to content

Commit 97bd1cc

Browse files
DOCSP-13838 crud projection (#66)
* added CRUD Pojection page
1 parent 87d6b12 commit 97bd1cc

File tree

7 files changed

+316
-18
lines changed

7 files changed

+316
-18
lines changed

source/fundamentals/crud/read-operations.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ Read Operations
88
- :doc:`/fundamentals/crud/read-operations/sort`
99
- :doc:`/fundamentals/crud/read-operations/skip`
1010
- :doc:`/fundamentals/crud/read-operations/limit`
11+
- :doc:`/fundamentals/crud/read-operations/project`
1112

1213
..
1314
- :doc:`/fundamentals/crud/read-operations/cursor`
14-
- :doc:`/fundamentals/crud/read-operations/project`
1515
- :doc:`/fundamentals/crud/read-operations/geo`
1616
- :doc:`/fundamentals/crud/read-operations/text`
1717

@@ -22,8 +22,8 @@ Read Operations
2222
/fundamentals/crud/read-operations/sort
2323
/fundamentals/crud/read-operations/skip
2424
/fundamentals/crud/read-operations/limit
25+
/fundamentals/crud/read-operations/project
2526
..
2627
/fundamentals/crud/read-operations/cursor
27-
/fundamentals/crud/read-operations/project
2828
/fundamentals/crud/read-operations/geo
2929
/fundamentals/crud/read-operations/text

source/fundamentals/crud/read-operations/limit.txt

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ returned from a read operation.
1919
Sample Data
2020
~~~~~~~~~~~
2121

22-
Run the following snippet to load the documents into the ``ratings``
23-
collection of the ``tea`` database:
22+
To run the examples in this guide, load these documents into the
23+
``ratings`` collection of the ``tea`` database with the following
24+
snippet:
2425

2526
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
2627
:language: go
@@ -142,14 +143,14 @@ After running this example, the output resembles the following:
142143
Additional Information
143144
----------------------
144145

145-
For more information on performing read operations, see our guide on
146-
:doc:`retrieving data </fundamentals/crud/read-operations/retrieve>`.
146+
For more information on the read operations used, see the following guides:
147147

148-
For information on specifying a sort, see our guide on :doc:`sorting
149-
results </fundamentals/crud/read-operations/sort>`.
148+
- :doc:`Retrieve Data </fundamentals/crud/read-operations/retrieve>`
149+
- :doc:`Sort Results </fundamentals/crud/read-operations/sort>`
150+
- :doc:`Skip Returned Results </fundamentals/crud/read-operations/skip>`
150151

151-
.. For information on skipping results, see our guide on :doc:`skipping
152-
.. returned results </fundamentals/crud/read-operations/skip>`.
152+
.. For more information on aggregation, see the
153+
.. :doc:`Aggregation </fundamentals/aggregation>` guide.
153154

154155
API Documentation
155156
~~~~~~~~~~~~~~~~~
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
==============================
2+
Specify Which Fields to Return
3+
==============================
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to specify which fields to return in a
17+
document from read operations.
18+
19+
Sample Data
20+
~~~~~~~~~~~
21+
22+
To run the examples in this guide, load these documents into the
23+
``ratings`` collection of the ``tea`` database with the following
24+
snippet:
25+
26+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/projection.go
27+
:language: go
28+
:dedent:
29+
:start-after: begin insertDocs
30+
:end-before: end insertDocs
31+
32+
.. include:: /includes/fundamentals/tea-sample-data-ending.rst
33+
34+
Projection
35+
----------
36+
37+
A projection specifies which fields to return in matched documents. It
38+
contains field names followed by a ``1`` (to include) or ``0`` (to
39+
exclude). Projections can only include or exclude fields.
40+
41+
You can specify a projection by passing one to the ``SetProjection()``
42+
function in the options of the following read operation functions:
43+
44+
- ``Find()``
45+
- ``FindOne()``
46+
- ``FindOneAndDelete()``
47+
- ``FindOneAndReplace()``
48+
- ``FindOneAndUpdate()``
49+
50+
.. tip::
51+
52+
If you don't specify a projection, the read operation returns all
53+
the fields in matched documents.
54+
55+
Exclude a Field
56+
~~~~~~~~~~~~~~~
57+
58+
To exclude a field, pass the field you want to exclude and a ``0`` to
59+
the ``SetProjection()`` function. For all fields you don't explicitly
60+
list in the projection, the driver includes them.
61+
62+
Example
63+
```````
64+
65+
The following example excludes the ``rating`` from the matched documents
66+
from the ``Find()`` function:
67+
68+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/projection.go
69+
:language: go
70+
:dedent:
71+
:start-after: begin exclude projection
72+
:end-before: end exclude projection
73+
74+
After running this example, the output resembles the following:
75+
76+
.. code-block:: none
77+
:copyable: false
78+
79+
//results truncated
80+
[{_id ObjectID("...")} {type Masala}]
81+
[{_id ObjectID("...")} {type Assam}]
82+
[{_id ObjectID("...")} {type Oolong}]
83+
[{_id ObjectID("...")} {type Earl Grey}]
84+
[{_id ObjectID("...")} {type English Breakfast}]
85+
86+
Include a Field
87+
~~~~~~~~~~~~~~~
88+
89+
To include a field, pass the field you want to include and a ``1`` to
90+
the ``SetProjection()`` function. For all fields you don't explicitly
91+
list in the projection, the driver excludes them.
92+
93+
.. important::
94+
95+
You can exclude the ``_id`` field even if you specified to include
96+
certain fields. By default, the driver includes the ``_id`` field.
97+
You must explicitly exclude the ``_id`` field if you do not want it
98+
returned.
99+
100+
.. _go-include-projection:
101+
102+
Example
103+
```````
104+
105+
The following example performs the following projection on the matched
106+
documents from the ``Find()`` function:
107+
108+
- Include the ``type`` and ``rating`` field
109+
- Exclude the ``_id`` field
110+
111+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/projection.go
112+
:language: go
113+
:dedent:
114+
:start-after: begin include projection
115+
:end-before: end include projection
116+
117+
After running this example, the output resembles the following:
118+
119+
.. code-block:: none
120+
:copyable: false
121+
122+
[{type Masala} {rating 10}]
123+
[{type Assam} {rating 5}]
124+
[{type Oolong} {rating 7}]
125+
[{type Earl Grey} {rating 8}]
126+
[{type English Breakfast} {rating 5}]
127+
128+
Aggregation
129+
~~~~~~~~~~~
130+
131+
You can also include the :manual:`$project </reference/operator/aggregation/project/>`
132+
stage to specify a projection in an aggregation pipeline.
133+
134+
Example
135+
```````
136+
137+
The following example performs the following projection on the matched
138+
documents from the ``Aggregate()`` function:
139+
140+
- Include the ``type`` and ``rating`` field
141+
- Exclude the ``_id`` field
142+
143+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/projection.go
144+
:language: go
145+
:dedent:
146+
:start-after: begin aggregate projection
147+
:end-before: end aggregate projection
148+
149+
After running this example, the output resembles the following:
150+
151+
.. code-block:: none
152+
:copyable: false
153+
154+
[{type Masala} {rating 10}]
155+
[{type Assam} {rating 5}]
156+
[{type Oolong} {rating 7}]
157+
[{type Earl Grey} {rating 8}]
158+
[{type English Breakfast} {rating 5}]
159+
160+
Additional Information
161+
----------------------
162+
163+
For more information on performing read operations, see our guide on
164+
:doc:`retrieving data </fundamentals/crud/read-operations/retrieve>`.
165+
166+
.. For more information on aggregation, see the
167+
.. :doc:`Aggregation </fundamentals/aggregation>` guide.
168+
169+
API Documentation
170+
~~~~~~~~~~~~~~~~~
171+
172+
For more information on any of the functions or types discussed in this
173+
guide, see the following API Documentation:
174+
175+
- `Find() <{+api+}/mongo#Collection.Find>`__
176+
- `FindOptions.SetProjection() <{+api+}/mongo/options#FindOptions.SetProjection>`__
177+
- `FindOne() <{+api+}/mongo#Collection.FindOne>`__
178+
- `FindOneAndDelete() <{+api+}/mongo#Collection.FindOneAndDelete>`__
179+
- `FindOneAndReplace() <{+api+}/mongo#Collection.FindOneAndReplace>`__
180+
- `FindOneAndUpdate() <{+api+}/mongo#Collection.FindOneAndUpdate>`__
181+
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__

source/fundamentals/crud/read-operations/retrieve.txt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ Read operations allow you to do the following:
2424
Sample Data
2525
~~~~~~~~~~~
2626

27-
Run the following snippet to load the documents into the ``ratings``
28-
collection of the ``tea`` database:
27+
To run the examples in this guide, load these documents into the
28+
``ratings`` collection of the ``tea`` database with the following
29+
snippet:
2930

3031
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
3132
:language: go

source/fundamentals/crud/read-operations/skip.txt

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ results from read operations.
1919
Sample Data
2020
~~~~~~~~~~~
2121

22-
Run the following snippet to load the documents into the ``ratings``
23-
collection of the ``tea`` database:
22+
To run the example in this guide, load these documents into the
23+
``ratings`` collection of the ``tea`` database with the following
24+
snippet:
2425

2526
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/skip.go
2627
:language: go
@@ -113,11 +114,13 @@ After running this example, the output resembles the following:
113114
Additional Information
114115
----------------------
115116

116-
For more information on performing read operations, see our guide on
117-
:doc:`retrieving data </fundamentals/crud/read-operations/retrieve>`.
117+
For more information on the read operations used, see the following guides:
118118

119-
For information on specifying a sort, see our guide on :doc:`sorting
120-
results </fundamentals/crud/read-operations/sort>`.
119+
- :doc:`Retrieve Data </fundamentals/crud/read-operations/retrieve>`
120+
- :doc:`Sort Results </fundamentals/crud/read-operations/sort>`
121+
122+
.. For more information on aggregation, see the
123+
.. :doc:`Aggregation </fundamentals/aggregation>` guide.
121124

122125
API Documentation
123126
~~~~~~~~~~~~~~~~~

source/fundamentals/crud/read-operations/sort.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,9 @@ For more information on performing read operations, see our guide on
202202
.. For information about sorting text, see our
203203
.. guide on :doc:`Text Search </fundamentals/crud/write-operations/text>`.
204204

205+
.. For more information on aggregation, see the
206+
.. :doc:`Aggregation </fundamentals/aggregation>` guide.
207+
205208
API Documentation
206209
~~~~~~~~~~~~~~~~~
207210

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"os"
8+
9+
"go.mongodb.org/mongo-driver/bson"
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/mongo/options"
12+
)
13+
14+
func main() {
15+
var uri string
16+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
17+
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
18+
}
19+
20+
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
21+
22+
if err != nil {
23+
panic(err)
24+
}
25+
defer func() {
26+
if err = client.Disconnect(context.TODO()); err != nil {
27+
panic(err)
28+
}
29+
}()
30+
31+
client.Database("tea").Collection("ratings").Drop(context.TODO())
32+
33+
// begin insertDocs
34+
coll := client.Database("tea").Collection("ratings")
35+
docs := []interface{}{
36+
bson.D{{"type", "Masala"}, {"rating", 10}},
37+
bson.D{{"type", "Assam"}, {"rating", 5}},
38+
bson.D{{"type", "Oolong"}, {"rating", 7}},
39+
bson.D{{"type", "Earl Grey"}, {"rating", 8}},
40+
bson.D{{"type", "English Breakfast"}, {"rating", 5}},
41+
}
42+
43+
result, err := coll.InsertMany(context.TODO(), docs)
44+
if err != nil {
45+
panic(err)
46+
}
47+
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
48+
//end insertDocs
49+
50+
fmt.Println("Exclude Projection:")
51+
{
52+
//begin exclude projection
53+
opts := options.Find().SetProjection(bson.D{{"rating", 0}})
54+
55+
cursor, err := coll.Find(context.TODO(), bson.D{}, opts)
56+
if err != nil {
57+
panic(err)
58+
}
59+
60+
var results []bson.D
61+
if err = cursor.All(context.TODO(), &results); err != nil {
62+
panic(err)
63+
}
64+
for _, result := range results {
65+
fmt.Println(result)
66+
}
67+
//end exclude projection
68+
}
69+
70+
fmt.Println("Include Projection:")
71+
{
72+
//begin include projection
73+
opts := options.Find().SetProjection(bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}})
74+
75+
cursor, err := coll.Find(context.TODO(), bson.D{}, opts)
76+
if err != nil {
77+
panic(err)
78+
}
79+
80+
var results []bson.D
81+
if err = cursor.All(context.TODO(), &results); err != nil {
82+
panic(err)
83+
}
84+
for _, result := range results {
85+
fmt.Println(result)
86+
}
87+
//end include projection
88+
}
89+
90+
fmt.Println("Aggregation Projection:")
91+
{
92+
// begin aggregate projection
93+
projectStage := bson.D{{"$project", bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}}}
94+
95+
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{projectStage})
96+
if err != nil {
97+
panic(err)
98+
}
99+
100+
var results []bson.D
101+
if err = cursor.All(context.TODO(), &results); err != nil {
102+
panic(err)
103+
}
104+
for _, result := range results {
105+
fmt.Println(result)
106+
}
107+
// end aggregate projection
108+
}
109+
}

0 commit comments

Comments
 (0)