How to connect to MongoDB locally using .NET console application

Introduction

In this article, you will learn how to connect to MongoDB locally using a .NET console application.

Tools

  1. Visual Studio 2022

Steps Involved

Perform the following steps to connect to MongoDB locally using the .NET console application in Visual Studio 2022.

  1. Open Visual Studio 2022.
  2. Click File -> New -> Project.
  3. Select the Console App template. Click Next.
  4. Enter the project name and click Next.
  5. Select the .NET 8.0 framework. Click Create.
  6. Add the following NuGet packages.
    MongoDB.Driver
  7. 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);
    }
  8. 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.


Recommended Free Ebook
Similar Articles