Implementing MongoDB with .NET

Introduction

MongoDB, a popular NoSQL database, is widely used for its flexibility, scalability, and performance. It allows for easy storage and retrieval of unstructured data, making it a great choice for modern applications. Combining MongoDB with .NET enables developers to build robust, high-performance applications with rich features. This article will guide you through implementing MongoDB in a .NET application.

Prerequisites

Before we dive in, make sure you have the following installed on your machine.

  1. .NET SDK: Download and install from the .NET official website.
  2. MongoDB: Download and install from the MongoDB official website.
  3. Visual Studio or VS Code: An IDE for .NET development.

Step 1. Setting Up the Project

Start by creating a new .NET project. Open your terminal or command prompt and run the following command.

dotnet new console -n MongoDBDemo

Navigate to the project directory.

cd MongoDBDemo

Step 2. Installing MongoDB Driver

To interact with MongoDB, you need to install the MongoDB.Driver NuGet package. Run the following command.

dotnet add package MongoDB.Driver

Step 3. Creating the Data Model

Create a simple data model representing the data you want to store in MongoDB. For this example, let's create a Book class.

public class Book
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public int Year { get; set; }
}

Step 4. Connecting to MongoDB

Next, you need to establish a connection to your MongoDB database. Create a MongoDB service class to manage the connection and operations.

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class MongoDBService
{
    private readonly IMongoCollection<Book> _booksCollection;

    public MongoDBService()
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var database = client.GetDatabase("LibraryDb");
        _booksCollection = database.GetCollection<Book>("Books");
    }

    public async Task<List<Book>> GetBooksAsync()
    {
        return await _booksCollection.Find(new BsonDocument()).ToListAsync();
    }

    public async Task<Book> GetBookByIdAsync(string id)
    {
        return await _booksCollection.Find<Book>(book => book.Id == id).FirstOrDefaultAsync();
    }

    public async Task CreateBookAsync(Book book)
    {
        await _booksCollection.InsertOneAsync(book);
    }

    public async Task UpdateBookAsync(string id, Book book)
    {
        await _booksCollection.ReplaceOneAsync(book => book.Id == id, book);
    }

    public async Task DeleteBookAsync(string id)
    {
        await _booksCollection.DeleteOneAsync(book => book.Id == id);
    }
}

Step 5. Performing CRUD Operations

Now, you can use the MongoDB service class to perform CRUD operations. Update your Program.cs to interact with MongoDB.

using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        var mongoDBService = new MongoDBService();

        // Create a new book
        var newBook = new Book
        {
            Title = "The Great Gatsby",
            Author = "F. Scott Fitzgerald",
            Year = 1925
        };
        await mongoDBService.CreateBookAsync(newBook);
        Console.WriteLine("Book created!");

        // Get all books
        var books = await mongoDBService.GetBooksAsync();
        Console.WriteLine("Books in database:");
        foreach (var book in books)
        {
            Console.WriteLine($"{book.Title} by {book.Author} (Year: {book.Year})");
        }

        // Update a book
        var bookToUpdate = books[0];
        bookToUpdate.Year = 1926;
        await mongoDBService.UpdateBookAsync(bookToUpdate.Id, bookToUpdate);
        Console.WriteLine("Book updated!");

        // Delete a book
        await mongoDBService.DeleteBookAsync(bookToUpdate.Id);
        Console.WriteLine("Book deleted!");
    }
}

Conclusion

In this article, we've walked through the steps of setting up and using MongoDB with .NET. We created a data model, connected to MongoDB, and implemented CRUD operations. This foundation enables you to build more complex applications with MongoDB and .NET.

By leveraging the power of MongoDB's flexible schema and the robustness of .NET, you can create scalable and high-performance applications. Explore MongoDB's rich feature set and .NET's capabilities to take your applications to the next level.