Skip to content

Commit 4a715b6

Browse files
committed
DOCSP-45003: Specify Fields to Include
1 parent 051e6ca commit 4a715b6

File tree

3 files changed

+247
-0
lines changed

3 files changed

+247
-0
lines changed

source/fundamentals/crud/read-operations.txt

+2
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ 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
Monitor Data Changes </fundamentals/crud/read-operations/change-streams>
1617

1718
- :ref:`csharp-retrieve`
19+
- :ref: `csharp-project`
1820
- :ref:`csharp-count-documents`
1921
- :ref:`csharp-change-streams`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
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 ``restaurants`` collection in the ``sample_restaurants``
31+
database 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
33+
:atlas:`Get Started with Atlas </getting-started>` guide.
34+
35+
The examples on this page use the following ``Restaurant`` and ``Address`` classes to model
36+
the documents in the collection:
37+
38+
.. literalinclude:: /includes/fundamentals/code-examples/Project.cs
39+
:start-after: start-model
40+
:end-before: end-model
41+
:language: csharp
42+
43+
Projection Types
44+
----------------
45+
46+
You can use a projection to specify which fields to include in a return
47+
document, or to specify which fields to exclude.
48+
49+
When specifying certain fields to include in a projection, all other fields are implicitly
50+
excluded (except the ``_id`` field, which is included by default). You cannot combine
51+
inclusion and exclusion statements in a single projection, unless you are excluding the
52+
``_id`` field.
53+
54+
To remove the ``_id`` field from the returned document, you must
55+
:ref:`explicitly exclude it <csharp-project-exclude-id>`.
56+
57+
Specify Fields to Include
58+
~~~~~~~~~~~~~~~~~~~~~~~~~
59+
60+
To specify the fields to include from the result, chain the ``Projection()`` method
61+
to the ``Find()`` method. When calling the ``Projection()`` method, you must pass in the
62+
projection definition as a parameter. You can construct a projection definition by using
63+
the ``Builders<T>.Projection.Include()`` method and passing in the field name to include
64+
as a parameter. This method can be chained to include multiple fields in the projection.
65+
66+
The following example uses the ``Find()`` method to find all restaurants in which the ``name``
67+
field value is ``"Emerald Pub"``. Then, the code calls the ``projection()`` and ``exclude()``
68+
methods to instruct the find operation to omit the ``name`` and ``address`` fields
69+
in the result:
70+
71+
.. io-code-block::
72+
:copyable: true
73+
74+
.. input:: /includes/fundamentals/code-examples/Project.cs
75+
:start-after: start-project-include
76+
:end-before: end-project-include
77+
:language: csharp
78+
:dedent:
79+
80+
.. output::
81+
:visible: false
82+
83+
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" }
84+
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" }
85+
86+
.. _csharp-project-exclude-id:
87+
88+
Exclude the ``_id`` Field
89+
~~~~~~~~~~~~~~~~~~~~~~~~~
90+
91+
When specifying fields to include, you can also exclude the ``_id`` field from
92+
the returned document.
93+
94+
The following example runs the same query as the preceding example, but
95+
excludes the ``_id`` field from the projection:
96+
97+
.. io-code-block::
98+
:copyable: true
99+
100+
.. input:: /includes/fundamentals/code-examples/Project.cs
101+
:start-after: start-project-include-without-id
102+
:end-before: end-project-include-without-id
103+
:language: csharp
104+
:dedent:
105+
106+
.. output::
107+
:visible: false
108+
109+
{ "cuisine" : "American", "name" : "Emerald Pub" }
110+
{ "cuisine" : "American", "name" : "Emerald Pub" }
111+
112+
Specify Fields to Exclude
113+
~~~~~~~~~~~~~~~~~~~~~~~~~
114+
115+
To specify the fields to include from the result, chain the ``Projection()`` method
116+
to the ``Find()`` method. You can exclude fields in your projection by using
117+
the ``Builders<T>.Projection.Exclude()`` method and passing in the field name to exclude
118+
as a parameter. This method can be chained to exclude multiple fields in the projection.
119+
120+
The following example uses the ``Find()`` method to find all restaurants in which the ``name``
121+
field value is ``"Emerald Pub"``. It then uses a projection to exclude the ``cuisine``
122+
field from the returned documents:
123+
124+
.. io-code-block::
125+
:copyable: true
126+
127+
.. input:: /includes/fundamentals/code-examples/Project.cs
128+
:start-after: start-project-exclude
129+
:end-before: end-project-exclude
130+
:language: csharp
131+
:dedent:
132+
133+
.. output::
134+
:visible: false
135+
136+
{ "_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" }
137+
{ "_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" }
138+
139+
Additional Information
140+
----------------------
141+
142+
To learn more about projections, see the :manual:`Project Fields guide
143+
</tutorial/project-fields-from-query-results/>` in the MongoDB Server Manual.
144+
145+
API Documentation
146+
~~~~~~~~~~~~~~~~~
147+
148+
To learn more about any of the functions or types discussed in this
149+
guide, see the following API Documentation:
150+
151+
- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`_
152+
- `Projection <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders-1.Projection.html>`_
153+
- `Include() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Include.html>`_
154+
- `Exclude() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Exclude.html>`_
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Bson.Serialization.Attributes;
3+
using MongoDB.Bson.Serialization.Conventions;
4+
using MongoDB.Driver;
5+
6+
public class LimitSortSkip
7+
{
8+
// Replace with your connection string
9+
private const string MongoConnectionString = "<connection string URI>";
10+
11+
public static void Main(string[] args)
12+
{
13+
var mongoClient = new MongoClient(MongoConnectionString);
14+
var database = mongoClient.GetDatabase("sample_restaurants");
15+
var collection = database.GetCollection<Restaurant>("restaurants");
16+
17+
{
18+
// start-project-include
19+
var filter = Builders<Restaurant>.Filter.Eq("name", "Emerald Pub");
20+
var projection = Builders<Restaurant>.Projection
21+
.Include("name")
22+
.Include("cuisine");
23+
24+
var results = collection.Find(filter).Project(projection).ToList();
25+
foreach (var result in results)
26+
{
27+
Console.WriteLine(result.ToJson());
28+
}
29+
// end-project-include
30+
}
31+
32+
{
33+
// start-project-include-without-id
34+
var filter = Builders<Restaurant>.Filter.Eq("name", "Emerald Pub");
35+
var projection = Builders<Restaurant>.Projection
36+
.Include("name")
37+
.Include("cuisine")
38+
.Exclude("_id");
39+
40+
var results = collection.Find(filter).Project(projection).ToList();
41+
foreach (var result in results)
42+
{
43+
Console.WriteLine(result.ToJson());
44+
}
45+
// end-project-include-without-id
46+
}
47+
48+
{
49+
// start-project-exclude
50+
var filter = Builders<Restaurant>.Filter.Eq("name", "Emerald Pub");
51+
var projection = Builders<Restaurant>.Projection
52+
.Exclude("cuisine");
53+
54+
var results = collection.Find(filter).Project(projection).ToList();
55+
foreach (var result in results)
56+
{
57+
Console.WriteLine(result.ToJson());
58+
}
59+
// end-project-exclude
60+
}
61+
62+
}
63+
}
64+
65+
// start-model
66+
public class Restaurant {
67+
public ObjectId? Id { get; set; }
68+
69+
[BsonElement("name")]
70+
public string? Name { get; set; }
71+
72+
[BsonElement("cuisine")]
73+
public string? Cuisine { get; set; }
74+
75+
[BsonElement("address")]
76+
public Address? Address { get; set; }
77+
}
78+
79+
public class Address
80+
{
81+
public string Building { get; set; }
82+
83+
[BsonElement("coord")]
84+
public double[] Coordinates { get; set; }
85+
86+
public string Street { get; set; }
87+
88+
[BsonElement("zipcode")]
89+
public string ZipCode { get; set; }
90+
}
91+
// end-model

0 commit comments

Comments
 (0)