Page Content

Tutorials

How to create a Collection in MongoDB using C#?

MongoDB using C#

Developers may use MongoDB effectively and intuitively with official drivers for several programming languages, including C#. By abstracting low-level aspects like BSON serialisation and network connectivity, these drivers provide a language-sensitive API that matches each language’s idioms while preserving consistent interfaces. Many MongoDB JavaScript shell operations can be transferred to the C# driver.

Installing the C# Driver

You will require the official C# driver in order to start working with MongoDB in C#. The C# driver is officially support although they do not give gem install commands for Ruby. The MongoDB driver is usually downloaded from NuGet by C# developers.

  1. Install .NET/C# development environment: Make sure it works.
  2. Install the MongoDB.Driver NuGet package: Installing the MongoDB.Driver NuGet package will provide you access to the essential features for working with MongoDB. Although NuGet is the usual approach for managing C# packages.

Like other official drivers, the C# driver manages the encoding and decoding of Binary JSON (BSON). The lightweight binary data format used by MongoDB for disc storage and network transmission is called BSON.

Connecting to MongoDB

MongoClient is used to connect C# applications to MongoDB. By default, newer C# driver versions (released after November 2012) use this class to assure safe writes and acknowledge all writes.

using MongoDB.Driver;
using MongoDB.Bson; // For BsonDocument, if you choose to use it directly
public class MongoDBExample
{
    private static IMongoClient _client;
    private static IMongoDatabase _database;
    private static IMongoCollection<BsonDocument> _usersCollection;
    public static void Main(string[] args)
    {
        // Establish connection to MongoDB server (default is localhost:27017)
        // This is a typical representation, adapting connection string logic from other drivers 
        _client = new MongoClient("mongodb://localhost:27017");
        // Get a reference to the 'tutorial' database
        // MongoDB automatically creates the database upon first insertion if it doesn't exist 
        _database = _client.GetDatabase("tutorial");
        // Get a reference to the 'users' collection
        _usersCollection = _database.GetCollection<BsonDocument>("users");
        Console.WriteLine("Connected to MongoDB successfully!");
        // --- Perform CRUD operations ---
        InsertDocuments();
        ReadDocuments();
        UpdateDocuments();
        DeleteDocuments();
        ManageCollections();
        Console.WriteLine("Example operations completed.");
    }
    // ... CRUD methods will go here ...
}

Basic CRUD Operations (Create, Read, Update, Delete)

Python dictionaries and Ruby hashes are two examples of computer languages that naturally represent MongoDB records as objects. BsonDocument or Plain Old C# Objects (POCOs), which the driver may automatically map, are two ways to represent documents in C#. BsonDocument is frequently used for demonstrations since it is straightforward and provides a direct parallel to MongoDB’s JSON-like format.

Create (Insert Documents)

Use InsertOneAsync for a single document or InsertManyAsync for several documents when adding new documents. The insert_one and insert_many ideas found in other drivers are reflected in these techniques.

public static void InsertDocuments()
    {
        // Insert a single document
        var document1 = new BsonDocument
        {
            { "name", "Alice Smith" },
            { "age", 30 },
            { "email", "alice.smith@example.com" }
        };
        _usersCollection.InsertOne(document1);
        // Insert multiple documents
        var document2 = new BsonDocument
        {
            { "name", "Bob Johnson" },
            { "age", 25 },
            { "email", "bob.johnson@example.com" }
        };
        var document3 = new BsonDocument
        {
            { "name", "Charlie Brown" },
            { "age", 35 },
            { "email", "charlie.brown@example.com" }
        };
        _usersCollection.InsertMany(new[] { document2, document3 });
        Console.WriteLine("\nDocuments inserted.");
    }

Read (Query Documents)

Like the locate method in the shell and other drivers, the locate method is used to retrieve documents. An IFindFluent object, a cursor-like interface that enables additional filtering, sorting, and projection, is returned.

public static void ReadDocuments()
    {
        Console.WriteLine("\nAll users:");
        // Retrieve all documents
        var allUsers = _usersCollection.Find(new BsonDocument()).ToList();
        foreach (var doc in allUsers)
        {
            Console.WriteLine(doc.ToJson()); // ToJson() for readable output
        }
        Console.WriteLine("\nUsers older than 28:");
        // Retrieve documents based on a condition (using MongoDB query operators like '$gt')
        var filter = Builders<BsonDocument>.Filter.Gt("age", 28);
        var usersOlderThan28 = _usersCollection.Find(filter).ToList();
        foreach (var doc in usersOlderThan28)
        {
            Console.WriteLine(doc.ToJson());
        }
        Console.WriteLine("\nOne user named Alice Smith:");
        // Find a single document
        var alice = _usersCollection.Find(new BsonDocument("name", "Alice Smith")).FirstOrDefault();
        if (alice != null)
        {
            Console.WriteLine(alice.ToJson());
        }
    }

Update Documents

A query selector to find documents and an update definition outlining modifications are necessary for update operations. $set and other update operators are frequently used.

public static void UpdateDocuments()
    {
        // Update a single document: Change Alice's email
        var filterAlice = Builders<BsonDocument>.Filter.Eq("name", "Alice Smith");
        var updateEmail = Builders<BsonDocument>.Update.Set("email", "alice@newdomain.com");
        _usersCollection.UpdateOne(filterAlice, updateEmail);
        Console.WriteLine("\nDocuments updated.");
    }

Delete Documents

A filter is used to determine which documents should be deleted using the DeleteOneAsync and DeleteManyAsync methods.

public static void DeleteDocuments()
    {
        // Delete a single document
        var filterBob = Builders<BsonDocument>.Filter.Eq("name", "Bob Johnson");
        _usersCollection.DeleteOne(filterBob);
        // Delete all documents with age greater than or equal to 35
        var filterAge = Builders<BsonDocument>.Filter.Gte("age", 35);
        _usersCollection.DeleteMany(filterAge);
        Console.WriteLine("\nDocuments deleted.");
    }

Database and Collection Management

Along with mirroring features from the shell and other drivers, the C# driver offers techniques for handling databases and collections.

public static void ManageCollections()
    {
        // List all databases (adapting command from shell/other drivers )
        Console.WriteLine("\nDatabases on server:");
        var databases = _client.ListDatabases().ToList();
        foreach (var dbInfo in databases)
        {
            Console.WriteLine($"- {dbInfo["name"]}");
        }
        // Drop a collection (adapting drop method from other drivers)
        // It's good practice to ensure the collection exists before dropping
        _database.DropCollection("users");
        Console.WriteLine("\n'users' collection dropped.");
    }

The C# driver enables sophisticated MongoDB capabilities like sharding for horizontal scalability and replication for high availability, while also being developer-friendly and abstracting low-level details. Newer versions of the C# driver are compatible with enhanced replica set member restrictions and sophisticated SCRAM-SHA-1 authentication. It also supports DBRefs for document linking. The C# driver is a powerful tool for creating scalable and efficient MongoDB applications because of its extensive support.

Index