Specify Fields To Return
On this page
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 sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the Get Started with the .NET/C# Driver.
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
explicitly exclude it.
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:
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()); }
{ "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" } { "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" }
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:
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()); }
{ "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:
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()); }
{ "_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 Project Fields guide in the MongoDB Server manual.
API Documentation
To learn more about any of the functions or types discussed in this guide, see the following API Documentation:
Sample Class
The code examples in this guide demonstrate how you can use builders to
create types to interact with documents in the sample collection plants.flowers
.
Documents in this collection are modeled by the following Flower
class:
public class Flower { public ObjectId Id { get; set; } public string Name { get; set; } public string Category { get; set; } public double Price { get; set; } public List<string> Season { get; set; } public double Stock { get; set; } public string Description { get; set; } }
Each builder class takes a generic type parameter
TDocument
which represents the type of document that you are working
with. In this guide, the Flower
class is the document type used in
each builder class example.
Create a Projection
The ProjectionDefinitionBuilder
class provides a type-safe interface for
defining a projection. Suppose you want to create a projection on the
Name
and Price
fields, but exclude the Id
field.
Use builders to create the projection definition with the typed variant:
var builder = Builders<Flower>.Projection; var projection = builder.Include(f => f.Name).Include(f => f.Price).Exclude(f => f.Id);
You can also use string-based field names to define the projection:
var builder = Builders<Flower>.Projection; var projection = builder.Include("Name").Include("Price").Exclude("Id");
Finally, you can use the Expression()
method to define the
projection:
var builder = Builders<Flower>.Projection; var projection = builder.Expression(f => new { Name = f.Name, Price = f.Price });
This definition has a return type of ProjectionDefinition<TDocument,
TProjection>
whereas the others return a
ProjectionDefinition<TDocument>
.
Lambda Expressions
The driver supports using lambda expressions to render projections. When
you define a Find()
projection with the Expression()
method to
create a lambda expression, the driver inspects the expression
to determine which fields are referenced and automatically constructs a
server-side projection to return only those fields.
You can also use lambda expressions to create new fields by performing
operations on values in your documents. The following example shows how
you can use a lambda expression to project a new Profit
field
using the Price
and Stock
fields:
var builder = Builders<Flower>.Projection; var projection = builder.Expression(f => new { Profit = f.Price * f.Stock });
Note
Id Field Exclusion
When you create a projection using a lambda expression, the output
automatically excludes the Id
field unless you explicitly include
is as a projection field.