In this guide, you can learn how to use the MongoDB .NET/C# Driver to retrieve data from a MongoDB collection by using read operations. You can call the Find()
method to retrieve documents that match a set of criteria.
This page includes a short interactive lab that demonstrates how to retrieve data by using the Find()
method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.
To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.
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.
The examples on this page use the following Restaurant
, Address
, and GradeEntry
classes as models:
public class Restaurant{ public ObjectId Id { get; set; } public string Name { get; set; } [BsonElement("restaurant_id")] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; }}
public class Address{ public string Building { get; set; } [BsonElement("coord")] public double[] Coordinates { get; set; } public string Street { get; set; } [BsonElement("zipcode")] public string ZipCode { get; set; }}
public class GradeEntry{ public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; }}
Note
The documents in the restaurants
collection use the snake-case naming convention. The examples in this guide use a ConventionPack
to deserialize the fields in the collection into Pascal case and map them to the properties in the Restaurant
class.
To learn more about custom serialization, see Custom Serialization.
Use the Find()
method to retrieve documents from a collection. The Find()
method takes a query filter and returns all matching documents. A query filter is an object that specifies the documents you want to retrieve in your query.
To learn more about query filters, see Create a Query Filter.
To find a single document in a collection, pass a query filter that specifies the criteria of the document you want to find, then chain the FirstOrDefault()
or FirstOrDefaultAsync()
method. If more than one document matches the query filter, these methods return the first matching document from the retrieved results. If no documents match the query filter the methods return null
.
var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
Tip First Document
The FirstOrDefault()
method returns the first document in natural order on disk if no sort criteria is specified.
To see a full example of using the Find()
method to find a single document, see Additional Information.
To find multiple documents in a collection, pass a query filter to the Find()
method that specifies the criteria of the documents you want to retrieve.
You can use a cursor to iterate over the documents returned by the Find()
method. A cursor is a mechanism that allows an application to iterate over database results while holding only a subset of them in memory at a given time. Cursors are useful when your Find()
method returns a large amount of documents.
To use a cursor to iterate over the documents, pass a query filter to the Find()
method that specifies the criteria of the documents you want to find, then chain the ToCursor()
or ToCursorAsync()
method. To view a synchronous or asynchronous example, select the corresponding tab.
var restaurants = _restaurantsCollection.Find(filter).ToCursor();
var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync();
If you are returning a small number of documents, or need your results returned as a List
object, use the ToList()
or ToListAsync()
methods.
To find multiple documents in a collection and hold them in memory as a list, pass a query filter to the Find()
method that specifies the criteria of the documents you want to find, then chain the ToList()
or ToListAsync()
method. To view a synchronous or asynchronous example, select the corresponding tab.
var restaurants = _restaurantsCollection.Find(filter).ToList();
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();
To see a full example of using the Find()
method to find multiple documents, see Additional Information.
To find all documents in a collection, pass an empty filter to the Find()
method.
var filter = Builders<Restaurant>.Filter.Empty;var allRestaurants = _restaurantsCollection.Find(filter);
To see a fully runnable example of using the Find()
method to find all documents, see Additional Information.
You can modify the behavior of the Find()
method by passing a FindOptions
object.
You can configure the commonly used options with the following methods:
Method
Description
BatchSize
Gets or sets the maximum number of documents within each batch returned in a query result. If batchSize
is not set, the Find()
method has an initial batch size of 101
documents and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger one. If you set batchSize
to a limit that results in batches larger than 16 MiB, this option has no effect and the Find()
method uses the default batch size.
Collation
Sets the collation options. See the
Collationsection of this page for more information.
Comment
Sets the comment to the query to make looking in the profiler logs easier.
Hint
Sets the hint for which index to use.
MaxTime
Sets the maximum execution time on the server for this operation.
To see a full list of available options, see FindOptions Properties.
To configure collation for your operation, create an instance of the Collation class.
The following table describes the parameters that the Collation
constructor accepts. It also lists the corresponding class property that you can use to read each setting's value.
Parameter
Description
Class Property
locale
Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see
Collation Locales and Default Parametersin the MongoDB Server Manual.
If you want to use simple binary comparison, use the Collation.Simple
static property to return a Collation
object with the locale
set to "simple"
.
Data Type: string
Locale
caseLevel
(Optional) Specifies whether to include case comparison.
When this argument is true
, the driver's behavior depends on the value of the strength
argument:
- If strength
is CollationStrength.Primary
, the driver compares base characters and case.
- If strength
is CollationStrength.Secondary
, the driver compares base characters, diacritics, other secondary differences, and case.
- If strength
is any other value, this argument is ignored.
When this argument is false
, the driver doesn't include case comparison at strength level Primary
or Secondary
.
Data Type: boolean
Default: false
CaseLevel
caseFirst
(Optional) Specifies the sort order of case differences during tertiary level comparisons.
Data Type:
CollationCaseFirstDefault: CollationCaseFirst.Off
CaseFirst
strength
Specifies the level of comparison to perform, as defined in the
ICU documentation.
Data Type:
CollationStrengthDefault: CollationStrength.Tertiary
Strength
numericOrdering
(Optional) Specifies whether the driver compares numeric strings as numbers.
If this argument is true
, the driver compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the driver treats the values as 10 and 2, and finds 10 to be greater.
If this argument is false
or excluded, the driver compares numeric strings as strings. For example, when comparing the strings "10" and "2", the driver compares one character at a time. Because "1" is less than "2", the driver finds "10" to be less than "2".
For more information, see
Collation Restrictionsin the MongoDB Server manual.
Data Type: boolean
Default: false
NumericOrdering
alternate
(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.
Data Type:
CollationAlternateDefault: CollationAlternate.NonIgnorable
(spaces and punctuation are considered base characters)
Alternate
maxVariable
(Optional) Specifies which characters the driver considers ignorable when the alternate
argument is CollationAlternate.Shifted
.
:
CollationMaxVariableDefault: CollationMaxVariable.Punctuation
(the driver ignores punctuation and spaces)
MaxVariable
normalization
(Optional) Specifies whether the driver normalizes text as needed.
Most text doesn't require normalization. For more information about normalization, see the
ICU documentation.
Data Type: boolean
Default: false
Normalization
backwards
(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.
Data Type: boolean
Default: false
Backwards
For more information about collation, see the Collation page in the MongoDB Server manual.
This example performs the following actions:
Finds all documents with "Pizza" in the cuisine
field
Sets the BatchSize
to 3
Stores the results in a cursor
Prints the documents referenced by the cursor
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");var findOptions = new FindOptions { BatchSize = 3 };using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor()){ foreach (var r in cursor.ToEnumerable()) { WriteLine(r.Name); }}
Pizza TownVictoria Pizza...
Tip Clean Up
Create a cursor with a using statement to automatically invoke the Dispose() method once the cursor is no longer in use.
To learn more about query filters, see Create a Query Filter.
To learn how to specify queries using LINQ, see LINQ Syntax for Aggregation Operations.
For runnable examples of the find operations, see the following usage examples:
To learn more about any of the methods or types discussed in this guide, see the following API Documentation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4