-
Notifications
You must be signed in to change notification settings - Fork 24
DOCSP-45003: Specify Fields to Include #291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4a715b6
DOCSP-45003: Specify Fields to Include
mcmorisi 4a6019b
Fix
mcmorisi db7c687
Fix
mcmorisi a6f039d
Fix
mcmorisi dbbabec
SA feedback
mcmorisi fde8219
Address technical feedback
mcmorisi 04dcc4e
Fix
mcmorisi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
.. _csharp-project: | ||
|
||
======================== | ||
Specify Fields To Return | ||
======================== | ||
|
||
.. contents:: On this page | ||
:local: | ||
:backlinks: none | ||
:depth: 2 | ||
:class: singlecol | ||
|
||
.. facet:: | ||
:name: genre | ||
:values: reference | ||
|
||
.. meta:: | ||
:keywords: read, filter, project, select | ||
|
||
Overview | ||
-------- | ||
|
||
In this guide, you can learn how to specify which fields to return from a read | ||
operation by using a **projection**. A projection is a document that specifies | ||
which fields MongoDB returns from a query. | ||
|
||
Sample Data | ||
~~~~~~~~~~~ | ||
|
||
The examples in this guide use the ``sample_restaurants.restaurants`` collection | ||
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a | ||
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`. | ||
|
||
Projection Types | ||
---------------- | ||
|
||
You can use a projection to specify which fields to include in a return | ||
document, or to specify which fields to exclude. | ||
|
||
When specifying certain fields to include in a projection, all other fields are implicitly | ||
excluded (except the ``_id`` field, which is included by default). You cannot combine | ||
inclusion and exclusion statements in a single projection, unless you are excluding the | ||
``_id`` field. | ||
|
||
To remove the ``_id`` field from the returned document, you must | ||
:ref:`explicitly exclude it <csharp-project-exclude-id>`. | ||
|
||
Specify Fields to Include | ||
~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
To specify the fields to include from the result, chain the ``Project()`` method | ||
to the ``Find()`` method. When calling the ``Project()`` method, you must pass in the | ||
projection definition as a parameter. You can construct a projection definition by using | ||
the ``Builders<T>.Projection.Include()`` method and passing in the field name to include | ||
as a parameter. This method can be chained to include multiple fields in the projection. | ||
|
||
The following example uses the ``Find()`` method to find all restaurants in which the ``name`` | ||
field value is ``"Emerald Pub"``. Then, the code calls the ``Project()`` | ||
method to instruct the find operation to include the ``name`` and ``cuisine`` fields | ||
in the result: | ||
|
||
.. io-code-block:: | ||
:copyable: true | ||
|
||
.. input:: /includes/fundamentals/code-examples/Project.cs | ||
:start-after: start-project-include | ||
:end-before: end-project-include | ||
:language: csharp | ||
:dedent: | ||
|
||
.. output:: | ||
:visible: false | ||
|
||
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" } | ||
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" } | ||
|
||
.. _csharp-project-exclude-id: | ||
|
||
Exclude the ``_id`` Field | ||
~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
When specifying fields to include, you can also exclude the ``_id`` field from | ||
the returned document. | ||
|
||
The following example runs the same query as the preceding example, but | ||
excludes the ``_id`` field from the projection: | ||
|
||
.. io-code-block:: | ||
:copyable: true | ||
|
||
.. input:: /includes/fundamentals/code-examples/Project.cs | ||
:start-after: start-project-include-without-id | ||
:end-before: end-project-include-without-id | ||
:language: csharp | ||
:dedent: | ||
|
||
.. output:: | ||
:visible: false | ||
|
||
{ "cuisine" : "American", "name" : "Emerald Pub" } | ||
{ "cuisine" : "American", "name" : "Emerald Pub" } | ||
|
||
Specify Fields to Exclude | ||
~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
To specify the fields to exclude from the result, chain the ``Project()`` method | ||
to the ``Find()`` method. You can exclude fields in your projection by using | ||
the ``Builders<T>.Projection.Exclude()`` method and passing in the field name to exclude | ||
as a parameter. This method can be chained to exclude multiple fields in the projection. | ||
|
||
The following example uses the ``Find()`` method to find all restaurants in which the ``name`` | ||
field value is ``"Emerald Pub"``. It then uses a projection to exclude the ``cuisine`` | ||
field from the returned documents: | ||
|
||
.. io-code-block:: | ||
:copyable: true | ||
|
||
.. input:: /includes/fundamentals/code-examples/Project.cs | ||
:start-after: start-project-exclude | ||
:end-before: end-project-exclude | ||
:language: csharp | ||
:dedent: | ||
|
||
.. output:: | ||
:visible: false | ||
|
||
{ "_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" } | ||
{ "_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" } | ||
|
||
Additional Information | ||
---------------------- | ||
|
||
To learn more about projections, see the :manual:`Project Fields guide | ||
</tutorial/project-fields-from-query-results/>` in the {+mdb-server+} manual. | ||
|
||
API Documentation | ||
~~~~~~~~~~~~~~~~~ | ||
|
||
To learn more about any of the functions or types discussed in this | ||
guide, see the following API Documentation: | ||
|
||
- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`_ | ||
- `Projection <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders-1.Projection.html>`_ | ||
- `Include() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Include.html>`_ | ||
- `Exclude() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Exclude.html>`_ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
using MongoDB.Bson; | ||
using MongoDB.Driver; | ||
|
||
public class Project | ||
{ | ||
// Replace with your connection string | ||
private const string MongoConnectionString = "<connection string URI>"; | ||
|
||
public static void Main(string[] args) | ||
{ | ||
var mongoClient = new MongoClient(MongoConnectionString); | ||
var database = mongoClient.GetDatabase("sample_restaurants"); | ||
var collection = database.GetCollection<BsonDocument>("restaurants"); | ||
|
||
{ | ||
// start-project-include | ||
var filter = Builders<BsonDocument>.Filter.Eq("name", "Emerald Pub"); | ||
var projection = Builders<BsonDocument>.Projection | ||
.Include("name") | ||
.Include("cuisine"); | ||
|
||
var results = collection.Find(filter).Project(projection).ToList(); | ||
foreach (var result in results) | ||
{ | ||
Console.WriteLine(result.ToJson()); | ||
} | ||
// end-project-include | ||
} | ||
|
||
{ | ||
// start-project-include-without-id | ||
var filter = Builders<BsonDocument>.Filter.Eq("name", "Emerald Pub"); | ||
var projection = Builders<BsonDocument>.Projection | ||
.Include("name") | ||
.Include("cuisine") | ||
.Exclude("_id"); | ||
|
||
var results = collection.Find(filter).Project(projection).ToList(); | ||
foreach (var result in results) | ||
{ | ||
Console.WriteLine(result.ToJson()); | ||
} | ||
// end-project-include-without-id | ||
} | ||
|
||
{ | ||
// start-project-exclude | ||
var filter = Builders<BsonDocument>.Filter.Eq("name", "Emerald Pub"); | ||
var projection = Builders<BsonDocument>.Projection | ||
.Exclude("cuisine"); | ||
|
||
var results = collection.Find(filter).Project(projection).ToList(); | ||
foreach (var result in results) | ||
{ | ||
Console.WriteLine(result.ToJson()); | ||
} | ||
// end-project-exclude | ||
} | ||
|
||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Something to consider is that projections don't play nicely with POCOs.
When you only return some of the fields from the server your POCO is incomplete. Depending on how the serialization is done either the missing fields will be
null
(or other suitable default value) in your POCO result or perhaps even an exception might be thrown for missing fields.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll update this page to avoid using POCOs