This guide shows you how to create an application that uses the .NET/C# Driver to connect to a MongoDB Atlas cluster. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official MongoDB drivers.
The .NET/C# driver lets you connect to and communicate with MongoDB clusters from a .NET application.
MongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB clusters. In this guide, we show you how to get started with your own free (no credit card required) cluster.
Follow the steps below to connect your .NET application with a MongoDB Atlas cluster.
Create a MongoDB Cluster
Set Up a Free Tier Cluster in Atlas
To set up your Atlas Free Tier Cluster required for this guide, complete the guide on MongoDB Atlas Setup.
After completing the steps in the Atlas guide, you have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster. You also have a connection string similar to the following in your copy buffer:
"mongodb+srv://<db_username>:<db_password>@cluster0.abc.mongodb.net/?retryWrites=true&w=majority"
Set Your Connection String
Run the following code at the command prompt to save your MongoDB connection string to an environment variable. This method is safer than including your credentials in your source code.
export MONGODB_URI="<your MongoDB URI>"
Note
PowerShell Environment Variables
If you are using Microsoft PowerShell, run the following command to save your connection string in an environment variable:
set MONGODB_URI="<your MongoDB URI>"
Important
Make sure to replace the <db_username> and <db_password> sections of the connection string with the username and password of your Atlas database user.
For more information about connection strings, see Connection Strings.
Set Up Your Project
Create the Project
Create a new directory and initialize your project with the dotnet new command, as follows:
mkdir csharp-quickstart cd csharp-quickstart dotnet new console
Add MongoDB as a Dependency
Use the dotnet add command to add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver
Query Your MongoDB Cluster from Your Application
Copy and paste the following code into the Program.cs file in your application. You can choose to query documents by using a BsonDocument or a Plain Old CLR Object (POCO). Select the corresponding tab to see an example of each approach:
using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Driver; var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI"); if (connectionString == null) { Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/get-started/create-connection-string"); Environment.Exit(0); } var client = new MongoClient(connectionString); var collection = client.GetDatabase("sample_mflix").GetCollection<BsonDocument>("movies"); var filter = Builders<BsonDocument>.Filter.Eq("title", "Back to the Future"); var document = collection.Find(filter).First(); Console.WriteLine(document.ToJson(new JsonWriterSettings { Indent = true }));
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI"); if (connectionString == null) { Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/get-started/create-connection-string"); Environment.Exit(0); } var client = new MongoClient(connectionString); var collection = client.GetDatabase("sample_mflix").GetCollection<Movie>("movies"); var filter = Builders<Movie>.Filter.Eq(m => m.Title, "Back to the Future"); var movie = collection.Find(filter).First(); Console.WriteLine($"Title: {movie.Title}"); Console.WriteLine($"Plot: {movie.Plot}"); Console.WriteLine($"Genres: {string.Join(", ", movie.Genres ?? [])}"); [] public class Movie { [] public ObjectId Id { get; set; } [] public string? Title { get; set; } [] public string? Plot { get; set; } [] public List<string>? Genres { get; set; } }
Tip
To learn more about using POCOs with the .NET/C# Driver, see the POCOs guide.
Run the application from your command line by using the following command:
dotnet run csharp-quickstart.csproj
The output includes details of the retrieved movie document. The following shows the output for each approach:
{ _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ... title: 'Back to the Future', ... }
Title: Back to the Future Plot: A young man is accidentally sent 30 years into the past... Genres: Adventure, Comedy, Sci-Fi
Tip
If you encounter an error or see no output, ensure that you specified the proper connection string, and that you loaded the sample data.
After completing this step, you have a working application that uses the .NET/C# Driver to connect to your MongoDB cluster, run a query on the sample data, and print out the result.
To learn more about connecting to Atlas with the .NET/C# Driver, see the Atlas driver connection guide and select C# from the Select your language dropdown.
Next steps
Learn how to read and modify data using the .NET/C# Driver in the CRUD Operations guide or how to perform common operations in Usage Examples.