In this section, we will explore how to use MongoDB with C#. We will cover the following topics:

  1. Setting up the environment
  2. Connecting to MongoDB
  3. Performing CRUD operations
  4. Practical exercises

  1. Setting up the Environment

Before we start coding, we need to set up our development environment.

Prerequisites

  • Visual Studio or Visual Studio Code
  • .NET SDK
  • MongoDB server (local or cloud-based like MongoDB Atlas)

Installing the MongoDB Driver for C#

To interact with MongoDB from a C# application, we need to install the MongoDB.Driver package. You can do this using the NuGet Package Manager in Visual Studio or by running the following command in the terminal:

dotnet add package MongoDB.Driver

  1. Connecting to MongoDB

Let's start by creating a simple C# console application that connects to a MongoDB database.

Example Code

using MongoDB.Bson;
using MongoDB.Driver;
using System;

namespace MongoDBWithCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Connection string to MongoDB server
            var connectionString = "mongodb://localhost:27017";
            
            // Create a MongoClient object
            var client = new MongoClient(connectionString);
            
            // Get the database (create if not exists)
            var database = client.GetDatabase("testdb");
            
            // Get the collection (create if not exists)
            var collection = database.GetCollection<BsonDocument>("testcollection");
            
            Console.WriteLine("Connected to MongoDB!");
        }
    }
}

Explanation

  • MongoClient: This class is used to connect to a MongoDB server.
  • GetDatabase: This method retrieves a database. If the database does not exist, it will be created.
  • GetCollection: This method retrieves a collection from the database. If the collection does not exist, it will be created.

  1. Performing CRUD Operations

Creating Documents

To insert a document into a MongoDB collection, we use the InsertOne method.

Example Code

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

collection.InsertOne(document);
Console.WriteLine("Document inserted!");

Reading Documents

To read documents from a MongoDB collection, we use the Find method.

Example Code

var filter = Builders<BsonDocument>.Filter.Eq("name", "John Doe");
var result = collection.Find(filter).FirstOrDefault();

if (result != null)
{
    Console.WriteLine(result.ToString());
}
else
{
    Console.WriteLine("No document found!");
}

Updating Documents

To update a document, we use the UpdateOne method.

Example Code

var filter = Builders<BsonDocument>.Filter.Eq("name", "John Doe");
var update = Builders<BsonDocument>.Update.Set("age", 31);

collection.UpdateOne(filter, update);
Console.WriteLine("Document updated!");

Deleting Documents

To delete a document, we use the DeleteOne method.

Example Code

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

collection.DeleteOne(filter);
Console.WriteLine("Document deleted!");

  1. Practical Exercises

Exercise 1: Insert Multiple Documents

Task: Write a program to insert multiple documents into a MongoDB collection.

Solution:

var documents = new List<BsonDocument>
{
    new BsonDocument { { "name", "Alice" }, { "age", 25 }, { "email", "[email protected]" } },
    new BsonDocument { { "name", "Bob" }, { "age", 28 }, { "email", "[email protected]" } }
};

collection.InsertMany(documents);
Console.WriteLine("Multiple documents inserted!");

Exercise 2: Find Documents with a Specific Condition

Task: Write a program to find all documents where the age is greater than 25.

Solution:

var filter = Builders<BsonDocument>.Filter.Gt("age", 25);
var results = collection.Find(filter).ToList();

foreach (var doc in results)
{
    Console.WriteLine(doc.ToString());
}

Exercise 3: Update Multiple Documents

Task: Write a program to update the email of all documents where the name is "Alice".

Solution:

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

collection.UpdateMany(filter, update);
Console.WriteLine("Multiple documents updated!");

Exercise 4: Delete Documents with a Specific Condition

Task: Write a program to delete all documents where the age is less than 30.

Solution:

var filter = Builders<BsonDocument>.Filter.Lt("age", 30);

collection.DeleteMany(filter);
Console.WriteLine("Multiple documents deleted!");

Conclusion

In this section, we learned how to set up a C# environment to work with MongoDB, connect to a MongoDB database, and perform CRUD operations. We also provided practical exercises to reinforce the concepts. In the next module, we will explore real-world applications of MongoDB with C#.

© Copyright 2024. All rights reserved