Skip to content

Commit 5cb3301

Browse files
committed
DOCSP-45003: Specify Fields to Include (#291)
(cherry picked from commit 79d61d8)
1 parent 1ccc49b commit 5cb3301

File tree

3 files changed

+208
-0
lines changed

3 files changed

+208
-0
lines changed

source/fundamentals/crud/read-operations.txt

+2
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@ Read Operations
1111
:caption: Read Operations
1212

1313
Retrieve Data </fundamentals/crud/read-operations/retrieve>
14+
/fundamentals/crud/read-operations/project
1415
Count Documents </fundamentals/crud/read-operations/count>
1516
/fundamentals/crud/read-operations/distinct
1617
Monitor Data Changes </fundamentals/crud/read-operations/change-streams>
1718

1819
- :ref:`csharp-retrieve`
20+
- :ref:`csharp-project`
1921
- :ref:`csharp-count-documents`
2022
- :ref:`csharp-distinct`
2123
- :ref:`csharp-change-streams`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
.. _csharp-project:
2+
3+
========================
4+
Specify Fields To Return
5+
========================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: read, filter, project, select
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to specify which fields to return from a read
24+
operation by using a **projection**. A projection is a document that specifies
25+
which fields MongoDB returns from a query.
26+
27+
Sample Data
28+
~~~~~~~~~~~
29+
30+
The examples in this guide use the ``sample_restaurants.restaurants`` collection
31+
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
32+
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`.
33+
34+
Projection Types
35+
----------------
36+
37+
You can use a projection to specify which fields to include in a return
38+
document, or to specify which fields to exclude.
39+
40+
When specifying certain fields to include in a projection, all other fields are implicitly
41+
excluded (except the ``_id`` field, which is included by default). You cannot combine
42+
inclusion and exclusion statements in a single projection, unless you are excluding the
43+
``_id`` field.
44+
45+
To remove the ``_id`` field from the returned document, you must
46+
:ref:`explicitly exclude it <csharp-project-exclude-id>`.
47+
48+
Specify Fields to Include
49+
~~~~~~~~~~~~~~~~~~~~~~~~~
50+
51+
To specify the fields to include from the result, chain the ``Project()`` method
52+
to the ``Find()`` method. When calling the ``Project()`` method, you must pass in the
53+
projection definition as a parameter. You can construct a projection definition by using
54+
the ``Builders<T>.Projection.Include()`` method and passing in the field name to include
55+
as a parameter. This method can be chained to include multiple fields in the projection.
56+
57+
The following example uses the ``Find()`` method to find all restaurants in which the ``name``
58+
field value is ``"Emerald Pub"``. Then, the code calls the ``Project()``
59+
method to instruct the find operation to include the ``name`` and ``cuisine`` fields
60+
in the result:
61+
62+
.. io-code-block::
63+
:copyable: true
64+
65+
.. input:: /includes/fundamentals/code-examples/Project.cs
66+
:start-after: start-project-include
67+
:end-before: end-project-include
68+
:language: csharp
69+
:dedent:
70+
71+
.. output::
72+
:visible: false
73+
74+
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" }
75+
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" }
76+
77+
.. _csharp-project-exclude-id:
78+
79+
Exclude the ``_id`` Field
80+
~~~~~~~~~~~~~~~~~~~~~~~~~
81+
82+
When specifying fields to include, you can also exclude the ``_id`` field from
83+
the returned document.
84+
85+
The following example runs the same query as the preceding example, but
86+
excludes the ``_id`` field from the projection:
87+
88+
.. io-code-block::
89+
:copyable: true
90+
91+
.. input:: /includes/fundamentals/code-examples/Project.cs
92+
:start-after: start-project-include-without-id
93+
:end-before: end-project-include-without-id
94+
:language: csharp
95+
:dedent:
96+
97+
.. output::
98+
:visible: false
99+
100+
{ "cuisine" : "American", "name" : "Emerald Pub" }
101+
{ "cuisine" : "American", "name" : "Emerald Pub" }
102+
103+
Specify Fields to Exclude
104+
~~~~~~~~~~~~~~~~~~~~~~~~~
105+
106+
To specify the fields to exclude from the result, chain the ``Project()`` method
107+
to the ``Find()`` method. You can exclude fields in your projection by using
108+
the ``Builders<T>.Projection.Exclude()`` method and passing in the field name to exclude
109+
as a parameter. This method can be chained to exclude multiple fields in the projection.
110+
111+
The following example uses the ``Find()`` method to find all restaurants in which the ``name``
112+
field value is ``"Emerald Pub"``. It then uses a projection to exclude the ``cuisine``
113+
field from the returned documents:
114+
115+
.. io-code-block::
116+
:copyable: true
117+
118+
.. input:: /includes/fundamentals/code-examples/Project.cs
119+
:start-after: start-project-exclude
120+
:end-before: end-project-exclude
121+
:language: csharp
122+
:dedent:
123+
124+
.. output::
125+
:visible: false
126+
127+
{ "_id" : ObjectId("..."), "address" : { "building" : "308", "coord" : [-74.008493599999994, 40.725807199999998], "street" : "Spring Street", "zipcode" : "10013" }, "borough" : "Manhattan", "grades" : [{ "date" : ISODate("2014-02-24T00:00:00Z"), "grade" : "A", "score" : 5 }, { "date" : ISODate("2013-08-26T00:00:00Z"), "grade" : "A", "score" : 13 }, { "date" : ISODate("2013-03-04T00:00:00Z"), "grade" : "A", "score" : 12 }, { "date" : ISODate("2012-06-25T00:00:00Z"), "grade" : "A", "score" : 10 }, { "date" : ISODate("2011-12-23T00:00:00Z"), "grade" : "A", "score" : 10 }, { "date" : ISODate("2011-07-26T00:00:00Z"), "grade" : "C", "score" : 32 }], "name" : "Emerald Pub", "restaurant_id" : "40367329" }
128+
{ "_id" : ObjectId("..."), "address" : { "building" : "18301", "coord" : [-73.791184999999999, 40.740119999999997], "street" : "Horace Harding Expressway", "zipcode" : "11365" }, "borough" : "Queens", "grades" : [{ "date" : ISODate("2014-05-07T00:00:00Z"), "grade" : "A", "score" : 12 }, { "date" : ISODate("2013-04-30T00:00:00Z"), "grade" : "A", "score" : 9 }, { "date" : ISODate("2012-03-01T00:00:00Z"), "grade" : "A", "score" : 13 }], "name" : "Emerald Pub", "restaurant_id" : "40668598" }
129+
130+
Additional Information
131+
----------------------
132+
133+
To learn more about projections, see the :manual:`Project Fields guide
134+
</tutorial/project-fields-from-query-results/>` in the {+mdb-server+} manual.
135+
136+
API Documentation
137+
~~~~~~~~~~~~~~~~~
138+
139+
To learn more about any of the functions or types discussed in this
140+
guide, see the following API Documentation:
141+
142+
- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`_
143+
- `Projection <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders-1.Projection.html>`_
144+
- `Include() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Include.html>`_
145+
- `Exclude() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Exclude.html>`_
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Driver;
3+
4+
public class Project
5+
{
6+
// Replace with your connection string
7+
private const string MongoConnectionString = "<connection string URI>";
8+
9+
public static void Main(string[] args)
10+
{
11+
var mongoClient = new MongoClient(MongoConnectionString);
12+
var database = mongoClient.GetDatabase("sample_restaurants");
13+
var collection = database.GetCollection<BsonDocument>("restaurants");
14+
15+
{
16+
// start-project-include
17+
var filter = Builders<BsonDocument>.Filter.Eq("name", "Emerald Pub");
18+
var projection = Builders<BsonDocument>.Projection
19+
.Include("name")
20+
.Include("cuisine");
21+
22+
var results = collection.Find(filter).Project(projection).ToList();
23+
foreach (var result in results)
24+
{
25+
Console.WriteLine(result.ToJson());
26+
}
27+
// end-project-include
28+
}
29+
30+
{
31+
// start-project-include-without-id
32+
var filter = Builders<BsonDocument>.Filter.Eq("name", "Emerald Pub");
33+
var projection = Builders<BsonDocument>.Projection
34+
.Include("name")
35+
.Include("cuisine")
36+
.Exclude("_id");
37+
38+
var results = collection.Find(filter).Project(projection).ToList();
39+
foreach (var result in results)
40+
{
41+
Console.WriteLine(result.ToJson());
42+
}
43+
// end-project-include-without-id
44+
}
45+
46+
{
47+
// start-project-exclude
48+
var filter = Builders<BsonDocument>.Filter.Eq("name", "Emerald Pub");
49+
var projection = Builders<BsonDocument>.Projection
50+
.Exclude("cuisine");
51+
52+
var results = collection.Find(filter).Project(projection).ToList();
53+
foreach (var result in results)
54+
{
55+
Console.WriteLine(result.ToJson());
56+
}
57+
// end-project-exclude
58+
}
59+
60+
}
61+
}

0 commit comments

Comments
 (0)