Overview
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.
Tip
Interactive Lab
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.
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.
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; } [] 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; } [] public double[] Coordinates { get; set; } public string Street { get; set; } [] 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.
Find Documents
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.
Find One Document
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.
Find Multiple Documents
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.
Note
Find All Documents
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.
Modify Find Behavior
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 |
|---|---|
| Gets or sets the maximum number of documents within each
batch returned in a query result. If |
| Sets the collation options. See the Collation section of this page for more information. |
| Sets the comment to the query to make looking in the profiler logs easier. |
| Sets the hint for which index to use. |
| Sets the maximum execution time on the server for this operation. |
To see a full list of available options, see FindOptions Properties.
Collation
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 |
|---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. |
|
| (Optional) Specifies whether to include case comparison. |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. |
|
| (Optional) Specifies which characters the driver considers ignorable when
the |
|
| (Optional) Specifies whether the driver normalizes text as needed. |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. |
|
For more information about collation, see the Collation page in the MongoDB Server manual.
Example
This example performs the following actions:
Finds all documents with "Pizza" in the
cuisinefieldSets the
BatchSizeto3Stores 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 Town Victoria 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.
Additional Information
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:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: