3 minute read

MongoDB, a popular NoSQL database, pairs excellently with C#, a versatile programming language, to create robust and scalable applications. This guide will introduce you to using MongoDB with C#, covering everything from basic operations to advanced features. You can find the project on GitHub

Getting Started with MongoDB in C#

To interact with MongoDB in a C# application, you’ll need the official MongoDB .NET Driver. Let’s start by setting up your environment.

1. Setting Up Your Project

Create a new C# project and install the MongoDB .NET Driver via NuGet Package Manager:

Install-Package MongoDB.Driver
2. Connecting to the Database

Connect to your MongoDB instance to start performing operations.

using MongoDB.Driver;

var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("mydatabase");
var collection = database.GetCollection<BsonDocument>("users");

This code connects to a MongoDB instance on localhost at port 27017, accessing the mydatabase database and users collection.

3. Inserting Documents

Insert documents into a collection using the InsertOne or InsertMany methods.

var document = new BsonDocument
{
    { "student_id", 10000 },
    {
        "scores",
        new BsonArray
        {
            new BsonDocument { { "type", "exam" }, { "score", _rnd.Next(1, 100) } },
            new BsonDocument { { "type", "quiz" }, { "score", _rnd.Next(1, 100) } },
            new BsonDocument { { "type", "homework" }, { "score", _rnd.Next(1, 100) } },
            new BsonDocument { { "type", "homework" }, { "score", _rnd.Next(1, 100) } }
        }
    },
    { "class_id", _rnd.Next(1, 500) }
};
collection.InsertOne(document);

For multiple documents:

var documents = new List<BsonDocument>
{
    new BsonDocument { { "name", "Mahesh Kumar Yadav" }, { "age", 27 }, { "email", "mahesh@example.com" } },
    new BsonDocument { { "name", "Mukesh Kumar" }, { "age", 31 }, { "email", "mukesh@example.com" } }
};
collection.InsertMany(documents);
4. Querying Documents

Retrieve documents using the Find method, which returns a cursor to matching documents.

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

Update documents using UpdateOne, UpdateMany, or ReplaceOne. Here’s an example updating Mahesh Kumar Yadav’s age.

var filter = Builders<BsonDocument>.Filter.Eq("name", "Mahesh Kumar Yadav");
var update = Builders<BsonDocument>.Update.Set("age", 30);
collection.UpdateOne(filter, update);

To update multiple documents:

var filter = Builders<BsonDocument>.Filter.Lt("age", 30);
var update = Builders<BsonDocument>.Update.Set("status", "young");
collection.UpdateMany(filter, update);
6. Deleting Documents

Remove documents using DeleteOne or DeleteMany. Here’s how to delete a single document:

var filter = Builders<BsonDocument>.Filter.Eq("name", "Mahesh Kumar Yadav");
collection.DeleteOne(filter);

To delete multiple documents:

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

Advanced MongoDB Scripting with C#

After mastering basic CRUD operations, explore MongoDB’s advanced features.

Aggregation Framework

The aggregation framework allows for complex data processing and analysis.

var pipeline = new[]
{
    new BsonDocument { { "$match", new BsonDocument("age", new BsonDocument("$gte", 25)) } },
    new BsonDocument { { "$group", new BsonDocument { { "_id", "$status" }, { "averageAge", new BsonDocument("$avg", "$age") } } } },
    new BsonDocument { { "$sort", new BsonDocument("averageAge", -1) } }
};
var result = collection.Aggregate<BsonDocument>(pipeline).ToList();
Indexing for Performance

Indexes speed up query performance. Create indexes to improve data retrieval efficiency.

var indexKeysDefinition = Builders<BsonDocument>.IndexKeys.Ascending("email");
collection.Indexes.CreateOne(new CreateIndexModel<BsonDocument>(indexKeysDefinition));

Create compound indexes on multiple fields:

var indexKeysDefinition = Builders<BsonDocument>.IndexKeys.Ascending("name").Descending("age");
collection.Indexes.CreateOne(new CreateIndexModel<BsonDocument>(indexKeysDefinition));
Using MongoDB Transactions

Transactions ensure that a series of operations either all succeed or all fail, maintaining data integrity.

using (var session = client.StartSession())
{
    session.StartTransaction();
    try
    {
        var collection = session.Client.GetDatabase("mydatabase").GetCollection<BsonDocument>("users");
        var filter = Builders<BsonDocument>.Filter.Eq("name", "Mahesh Kumar Yadav");
        var update = Builders<BsonDocument>.Update.Set("age", 28);
        collection.UpdateOne(filter, update);

        filter = Builders<BsonDocument>.Filter.Eq("name", "Mukesh Kumar");
        update = Builders<BsonDocument>.Update.Set("age", 32);
        collection.UpdateOne(filter, update);

        session.CommitTransaction();
    }
    catch (Exception)
    {
        session.AbortTransaction();
        throw;
    }
}

Conclusion

Using MongoDB with C# enhances your ability to manage and manipulate data efficiently. From basic CRUD operations to advanced data processing with the aggregation framework, mastering these techniques will empower you to leverage the full potential of MongoDB. As you gain proficiency, explore further optimizations and advanced features to meet your application’s needs. Happy coding!

You can find the complete project on GitHub.

Leave a comment

Your email address will not be published. Required fields are marked *

Loading...