MongoDB through C# – Using the Official Library

MongoDB through C# – Using the Official Library

MongoDB is a popular NoSQL database, which means it doesn’t use tables like traditional databases. Instead, it saves data as ‘documents’, which are like flexible data entries. If you’re using C# and want to work with MongoDB, there’s an official library made just for that. In this post, we’ll check out this library, see some basic MongoDB info, and walk through some C# code examples for common tasks.

In MongoDB, data is saved in collections as documents. Think of collections like folders on your computer, and documents like files in those folders. But here, each document can have different data inside.

To get started, you first need to add the official MongoDB library to your C# project. You can do this with NuGet:

Install-Package MongoDB.Driver

Simple C# Code for MongoDB Tasks

Connecting to MongoDB:

var client = new MongoClient("your_connection_string_here");
var database = client.GetDatabase("your_database_name");
var collection = database.GetCollection<BsonDocument>("your_collection_name");

Insert Data

var document = new BsonDocument
{
    { "name", "John" },
    { "age", 30 },
    { "address", "123 Street Ave" }
};
collection.InsertOne(document);

Read Data

var filter = Builders<BsonDocument>.Filter.Eq("name", "John");
var result = collection.Find(filter).ToList();
foreach (var doc in result)
{
    Console.WriteLine(doc.ToString());
}

Update Data

var filter = Builders<BsonDocument>.Filter.Eq("name", "John");
var update = Builders<BsonDocument>.Update.Set("age", 31);  // Changing age to 31
collection.UpdateOne(filter, update);

and another way to update data

var newDocument = new BsonDocument
{
    { "name", "John" },
    { "age", 32 },
    { "address", "456 New Street" }
};
collection.ReplaceOne(filter, newDocument);

Remove data. This is the simple way of removing data:

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

and alternatively, you can do this:

collection.DeleteMany(filter);

If you want MongoDB to find data faster, you can set up an index on some data fields. However, learn more about indexes first before using it. Here’s how you create an index:

var indexData = Builders<BsonDocument>.IndexKeys.Ascending("name");  // Setting up index for the 'name' field
collection.CreateIndexes(new CreateIndexModel<BsonDocument>(indexData));

Suleyman Cabir Ataman, PhD

Sharing on social media:

Leave a Reply