@@ -19,23 +19,20 @@ These two methods of projection are mutually exclusive: if you
19
19
explicitly include fields, you cannot explicitly exclude fields, and
20
20
vice versa.
21
21
22
- Follow the instructions in the examples below to insert data into
23
- a collection and use a projection to return only specific fields.
24
- Consider a collection containing documents that describe varieties of
25
- fruit. To insert this data into a collection, run the following
26
- operation:
22
+ Consider the following collection containing documents that describe
23
+ varieties of fruit:
27
24
28
25
.. code-block:: javascript
29
26
30
- await fruits.insertMany( [
31
- { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
32
- { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
33
- { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
34
- { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
35
- ]);
27
+ [
28
+ { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
29
+ { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
30
+ { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
31
+ { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
32
+ ]
36
33
37
- Pass the following projection to only return the ``name`` field of each
38
- document:
34
+ In the following query, pass the projection to only return the ``name``
35
+ field of each document:
39
36
40
37
.. code-block:: javascript
41
38
:emphasize-lines: 2
@@ -95,3 +92,26 @@ the following results:
95
92
{ "name": "bananas" }
96
93
{ "name": "oranges" }
97
94
{ "name": "avocados" }
95
+
96
+ You can also specify multiple fields to include in your projection. Note: the
97
+ order in which you specify the fields in the projection does not alter the
98
+ order in which they are returned.
99
+
100
+ .. code-block:: javascript
101
+
102
+ const projection = { _id: 0, rating: 1, name: 1 };
103
+ const cursor = collection.find().project(projection);
104
+ await cursor.forEach(console.dir);
105
+
106
+ This example that identifies two fields to include in the projection yields
107
+ the following results:
108
+
109
+ .. code-block:: javascript
110
+
111
+ { "name": "apples", "rating": 3 }
112
+ { "name": "bananas", "rating": 1 }
113
+ { "name": "oranges", "rating": 2 }
114
+ { "name": "avocados", "rating": 5 }
115
+
116
+ For additional projection examples, see the
117
+ :manual:`MongoDB Manual page on Project Fields to Return from Query </tutorial/project-fields-from-query-results/>`.
0 commit comments