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

Retrieve Data

On this page

  • Overview
  • Sample Data
  • Find Documents
  • Find One Document
  • Find Multiple Documents
  • Modify Find Behavior
  • Example
  • Additional Information
  • API Documentation

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.

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 Quick Start.

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 camel-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 Specify a Query.

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 = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();

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 = await _restaurantsCollection.Find(filter).ToCursorAsync();
var restaurants = _restaurantsCollection.Find(filter).ToCursor();

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 = await _restaurantsCollection.Find(filter).ToListAsync();
var restaurants = _restaurantsCollection.Find(filter).ToList();

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.

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 number of documents to hold in a cursor at a given time.
Collation
Sets the collation options.
Comment
Sets the comment to the query. To learn more about query comments, see the $comment page.
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.

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 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.

To learn more about query filters, see Specify a Query.

To learn how to specify queries using LINQ, see LINQ.

To view runnable examples of the Find() method, see the Find a Document page.

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

Back

Read Operations