MongoDB CRUD Tutorials in C#: A Step-by-Step Guide

In this tutorial, we’ll explore the basics of performing CRUD (Create, Read, Update, Delete) operations in MongoDB using C#.

Posted on

MongoDB is a NoSQL database known for its flexibility and scalability, and C# is a versatile programming language. In this tutorial, we’ll explore the basics of performing CRUD (Create, Read, Update, Delete) operations in MongoDB using C#. We’ll cover the following steps:

  1. Setting Up Your Environment:

    • Installing MongoDB.
    • Setting up your C# development environment.
  2. Connecting to MongoDB:

    • Creating a connection to your MongoDB server.
  3. Creating a Collection:

    • Writing C# code to create a collection in your MongoDB database.
  4. Inserting Data:

    • Demonstrating how to insert data into the collection.
  5. Querying Data:

    • Retrieving data from the collection.
  6. Updating Data:

    • Modifying existing documents in the collection.
  7. Deleting Data:

    • Deleting documents from the collection.

1. Setting Up Your Environment

Installing MongoDB

Setting Up Your C# Development Environment

  • Install Visual Studio or Visual Studio Code, and ensure you have the .NET SDK installed.

2. Connecting to MongoDB

To connect to your MongoDB server from a C# application, you can use the official MongoDB C# driver (MongoDB.Driver). Install it using NuGet Package Manager or the .NET CLI:

dotnet add package MongoDB.Driver

Now, let’s create a connection to your MongoDB server:

using System;
using MongoDB.Driver;

class Program
{
    static void Main()
    {
        string connectionString = "mongodb://localhost:27017";
        MongoClient client = new MongoClient(connectionString);

        try
        {
            IMongoDatabase database = client.GetDatabase("mydatabase");
            Console.WriteLine("Connected to MongoDB!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Replace localhost:27017 with your MongoDB server address and port.

3. Creating a Collection

In MongoDB, data is stored in collections. Let’s create a collection named users:

IMongoDatabase database = client.GetDatabase("mydatabase");
IMongoCollection<BsonDocument> usersCollection = database.GetCollection<BsonDocument>("users");
Console.WriteLine("Collection 'users' created!");

This code creates a users collection in your MongoDB database.

4. Inserting Data

Now, let’s insert a user into the users collection:

var userDocument = new BsonDocument
{
    { "name", "John Doe" },
    { "email", "[email protected]" }
};

usersCollection.InsertOne(userDocument);
Console.WriteLine("Document inserted!");

This code inserts a user with the name “John Doe” and email “[email protected]” into the users collection.

5. Querying Data

Let’s retrieve data from the users collection:

var filter = new BsonDocument();
var users = usersCollection.Find(filter).ToList();

foreach (var user in users)
{
    Console.WriteLine($"Name: {user["name"]}, Email: {user["email"]}");
}

This code queries and displays all documents in the users collection.

6. Updating Data

Now, let’s update a user’s email address:

var updateFilter = Builders<BsonDocument>.Filter.Eq("name", "John Doe");
var update = Builders<BsonDocument>.Update.Set("email", "[email protected]");

usersCollection.UpdateOne(updateFilter, update);
Console.WriteLine("Document updated!");

This code updates the email address of the user with the name “John Doe” in the users collection.

7. Deleting Data

Let’s delete a user from the users collection:

var deleteFilter = Builders<BsonDocument>.Filter.Eq("name", "John Doe");

usersCollection.DeleteOne(deleteFilter);
Console.WriteLine("Document deleted!");

This code deletes the user with the name “John Doe” from the users collection.

With these CRUD operations, you have a solid foundation for working with MongoDB in your C# applications. Feel free to extend and adapt these examples to meet the requirements of your specific project. MongoDB’s flexible schema and scalability make it a powerful choice for various application scenarios.