Introduction
In this article, you will learn how to connect to MongoDB locally using a .NET console application.
Tools
- Visual Studio 2022
Steps Involved
Perform the following steps to connect to MongoDB locally using the .NET console application in Visual Studio 2022.
- Open Visual Studio 2022.
- Click File -> New -> Project.
- Select the Console App template. Click Next.
- Enter the project name and click Next.
- Select the .NET 8.0 framework. Click Create.
- Add the following NuGet packages.
MongoDB.Driver
- Open Program.cs and replace the code with the following.
using MongoDB.Bson;
using MongoDB.Driver;
string connectionString = "mongodb://localhost:27017/";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
Console.WriteLine("Connecting to MongoDB...");
try
{
var client = new MongoClient(settings);
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("connector-types");
var document= new BsonDocument { { "_id", "sqlserver" }, { "Description", "Connects to a SQL Server database instance." }, { "Name", "SQL Server" } };
collection.InsertOne(document);
Console.WriteLine("Document inserted successfully.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
Console.WriteLine(ex.StackTrace);
}
- Hit F5 to execute the application. An item was created in the MongoDB successfully.
![MongoDB]()
Summary
This article describes how to connect to MongoDB locally using .NET console application in Visual Studio 2022.