Docs Menu
Docs Home
/ / /
C#/.NET
/ /

Specify Fields To Return

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.

The examples on this page use the sample_mflix.movies 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.

The following class represents the documents in the sample_mflix.movies collection:

public class Movie
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public List<string> Genres { get; set; }
public string Type { get; set; }
public string Plot { get; set; }
public List<BsonDocument> Highlights { get; set; }
public string Score { get; set; }
[BsonElement("scoreDetails")]
public SearchScoreDetails ScoreDetails { get; set; }
[BsonElement("searchScoreDetails")]
public SearchScoreDetails SearchScoreDetails { get; set; }
[BsonElement("paginationToken")]
public string PaginationToken { get; set; }
public List<string> Cast { get; set; }
[BsonElement("plot_embedding")]
public float[] PlotEmbedding { get; set; }
}

To create a projection, perform the following steps:

  1. Use the Builders<TDocument>.Projection static property to create a ProjectionDefinitionBuilder<TDocument> object, where TDocument represents the C# class that the collection's documents map to. The ProjectionDefinitionBuilder class provides a type-safe interface for defining a projection.

  2. Chain projection methods from the ProjectionDefinitionBuilder<TDocument> object to specify which fields to include or exclude from the returned documents.

  3. Store the resulting ProjectionDefinition<TDocument> object in a variable.

  4. Pass the variable to the Project() method after performing the find or aggregation operation.

The following sections describe the methods that you can chain from your ProjectionDefinitionBuilder<TDocument> object.

The following methods let you specify which fields to include or exclude from the returned documents.

The ElemMatch() method limits the contents of an array field from the query results to contain only the first element matching a specified condition. This is equivalent to projecting an array element by using the $elemMatch operator in the MongoDB Query API.

For a code example that uses the ElemMatch() method, see $elemMatch in the MongoDB Server manual.

The Expression() method lets you specify the structure of the returned documents by using a lambda expression. This is equivalent to specifying the structure of the returned documents in the $project aggregation stage in the MongoDB Query API.

For a code example that uses the Expression() method, see $project in the MongoDB Server manual.

Note

Id Field Exclusion

When you use a lambda expression to create a projection, the output automatically excludes the Id field unless you explicitly include it.

The Exclude() method lets you specify a field to exclude from the returned documents. This is equivalent to excluding a field in the $project aggregation stage in the MongoDB Query API. You cannot combine inclusion and exclusion statements in a single projection unless you are excluding the _id field.

For a code example that uses the Exclude() method, see $project in the MongoDB Server manual.

Note

Explicitly Exclude _id Field

Returned documents include the _id field unless you explicitly exclude it. The only exception to this is when you use the Expression() method to create a projection.

The Include() method lets you specify a field to include in the returned documents. This is equivalent to including a field in the $project aggregation stage in the MongoDB Query API.

For a code example that uses the Include() method, see $project in the MongoDB Server manual.

The Slice() method specifies the number of elements of a list or array to return in the query result field. This is equivalent to using the $slice operator in the MongoDB Query API.

The following code example uses the Slice() method to return the first three elements of the Cast list in the returned document's cast array:

var filter = Builders<Movie>.Filter.Text("future");
var projection = Builders<Movie>
.Projection
.Slice(m => m.Cast, 3)
.Include(m => m.Cast);
var results = movieCollection.Find(filter)
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "573a1398f29313caabceb500"
},
"title": "Back to the Future Part II",
"cast": [
"Michael J. Fox",
"Christopher Lloyd",
"Lea Thompson"
]
}

To return elements from the end of a collection, pass a negative integer to the Slice() method. The following code example returns the last three elements of the Cast list in the returned document's cast array:

var filter = Builders<Movie>.Filter.Text("future");
var projection = Builders<Movie>
.Projection
.Slice(m => m.Cast, -3)
.Include(m => m.Title);
var results = movieCollection.Find(filter)
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "573a1398f29313caabceb500"
},
"title": "Back to the Future Part II",
"cast": [
"Lea Thompson",
"Thomas F. Wilson"
]
}

To skip a specified number of elements in a collection, pass the number of elements to skip as the first parameter and the number of elements to return as the second parameter. The following code example skips the first element in the Cast list and returns the next three elements in the cast array:

var filter = Builders<Movie>.Filter.Text("future");
var projection = Builders<Movie>
.Projection
.Slice(m => m.Cast, 1, 3)
.Include(m => m.Title);
var results = movieCollection.Find(filter)
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "573a1398f29313caabceb500"
},
"title": "Back to the Future Part II",
"cast": [
"Christopher Lloyd",
"Lea Thompson",
"Thomas F. Wilson"
]
}

To learn more about the $slice operator, see $slice in the MongoDB Server manual.

The following methods let you specify which metadata fields to include or exclude from the returned documents. Metadata fields are hidden by default.

The Meta() method lets you specify a metadata field to include in the returned documents. This is equivalent to including a metadata field by using the $meta operator in the MongoDB Query API.

The following code example adds the textScore metadata field to the returned documents as a field named score:

var filter = Builders<Movie>.Filter.Text("future");
var projection = Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
.Meta(field: "score", metaFieldName: "textScore");
var results = movieCollection.Find(filter)
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "..."
},
"plot": "...",
"title": "...",
"score": "..."
}

Note

Atlas Search Only

This method is available only when projecting the results of an Atlas Search.

The MetaSearchHighlights() includes search highlights in the returned documents. This is equivalent to projecting search highlights by using a { "$meta": "searchHighlights" } object in the MongoDB Query API. To retrieve search highlights, you must create a SearchHighlightOptions object that specifies the search field, and then pass this object to the Search() method.

The following code example retrieves search highlights for the plot field, then includes these highlights in a property named Highlights in the returned documents:

var filter = Builders<Movie>.Search.Text(path: m => m.Plot, query: "future");
var projection = Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
.MetaSearchHighlights(m => m.Highlights);
var results = movieCollection
.Aggregate()
.Search(filter, new SearchHighlightOptions<Movie> (m => m.Plot))
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "573a13def29313caabdb5661"
},
"plot": "She Can See Her Future, But Can't Escape Her Past.",
"title": "West",
"highlights": [
{
"score": 1.286744475364685,
"path": "plot",
"texts": [
{
"value": "She Can See Her ",
"type": "text"
},
{
"value": "Future",
"type": "hit"
},
{
"value": ", But Can't Escape Her Past.",
"type": "text"
}
]
}
]
}

To learn more about search highlights, see Highlight Search Terms in Results in the Atlas documentation.

Note

Atlas Search Only

This method is available only when projecting the results of an Atlas Search.

The MetaSearchScore() method includes search scores in the returned documents. This is equivalent to projecting search scores by using a { "$meta": "searchScore" } object in the MongoDB Query API.

The following code example projects each document's search score in a field named score:

var filter = Builders<Movie>.Search.Text(m => m.Plot, "future");
var projection = Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
.MetaSearchScore(m => m.Score);
var results = movieCollection
.Aggregate()
.Search(filter)
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "573a13def29313caabdb5661"
},
"plot": "She Can See Her Future, But Can't Escape Her Past.",
"title": "West",
"score": 2.8259084224700928
}

To learn more about search scores, see Score the Documents in the Returned Documents.

Note

Atlas Search Only

This method is available only when projecting the results of an Atlas Search.

The MetaSearchScoreDetails() includes details about the search scores in the returned documents. This is equivalent to projecting search score details by using a { "$meta": "searchScoreDetails" } object in the MongoDB Query API.

To retrieve score details, create a SearchOptions object with its ScoreDetails property set to true, and then pass this object to the Search() method. The following code example shows this process by projecting each document's search score details in a field named searchScoreDetails:

var filter = Builders<Movie>.Search.Text(m => m.Plot, "future");
var projection = Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
.MetaSearchScore(m => m.Score)
.MetaSearchScoreDetails(m => m.SearchScoreDetails);
var results = movieCollection
.Aggregate()
.Search(filter, new SearchOptions<Movie>() { ScoreDetails = true})
.Project(projection)
.Limit(1)
.ToList();
{
"_id": {
"$oid": "573a13def29313caabdb5661"
},
...
"scoreDetails": {
"value": 2.8259084224700928,
"description": "$type:string/plot:future [BM25Similarity], result of:",
"details": [
{
"value": 2.8259084224700928,
"description": "score(freq=1.0), computed as boost * idf * tf from:",
"details": [
...
}

To learn more about search score details, see Return the Score Details in the Atlas documentation.

Note

Atlas Search Only

This method is available only when projecting the results of an Atlas Search.

The MetaSearchSequenceToken() method includes a token in the returned documents that represents a point in the search sequence. This is equivalent to projecting the search sequence token by using a { "$meta": "searchSequenceToken" } object in the MongoDB Query API. You can use this token to perform additional searches before or after the specified point.

The following code example projects each document's search sequence token in a property named PaginationToken:

var filter = Builders<Movie>.Search.Text(m => m.Plot, "future");
var projection = Builders<Movie>.Projection
.Include(m => m.Title)
.Include(m => m.Plot)
.MetaSearchSequenceToken(m => m.PaginationToken);
var results = movieCollection
.Aggregate()
.Search(filter)
.Limit(1)
.Project(projection)
.ToList();
{
"_id": {
"$oid": "573a13def29313caabdb5661"
},
"plot": "She Can See Her Future, But Can't Escape Her Past.",
"title": "West",
"paginationToken": "CIeaARWv2zRAIg5aDFc6E97ykxPKq9tWYQ=="
}

To learn more about search sequence tokens, see Paginate Search Results

The MetaTextScore() method includes the $text search scores in the returned documents. This is equivalent to projecting the text search score by using a { "$meta": "textScore" } object in the MongoDB Query API.

For a code example that uses the MetaTextScore() method, see $meta in the MongoDB Server manual.

Note

Atlas Vector Search Only

This method is available only when projecting the results of an Atlas Vector Search.

The MetaVectorSearchScore() method includes the Atlas Vector Search scores in the returned documents. This is equivalent to projecting the Vector Search score by using a { "$meta": "vectorSearchScore" } object in the MongoDB Query API.

For a code example that uses the MetaVectorSearchScore() method, see Atlas Vector Search.

To learn more about Atlas Vector Search scores, see Score the Documents in the Returned Documents in the Atlas documentation.

Note

Atlas Search Only

This method is available only when projecting the results of an Atlas Search.

The SearchMeta() method includes a metadata results document. The structure of this document depends on the type of the results. This is equivalent to projecting the metadata results document by using the $searchMeta aggregation stage or the $$SEARCH_META aggregation variable in the MongoDB Query API.

For a code example that uses the SearchMeta() method, see How to Use Facets with Atlas Search in the Atlas documentation.

To learn more about $searchMeta and $$SEARCH_META, see the following Atlas documentation:

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Specify Documents to Return

On this page