Here is a simple example of how to use MongoDB with C#.

What is MongoDB?

MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema.

How to use the MongoDB?

Because MongoDB has to run on a server, you then have two options: install it or use an instance on the Cloud. I would suggest to follow this link if you want to install it locally or on your server. But according to me, the best option is to connect to MongoDB Atlas and create a free cluster (limited to 512 MB of Storage).

Simple tutorial using MongoDB with C#

Here we will try all the simple CRUD operations. The main advantage is that you don’t have to do anything to create your database or collections, they will be created automatically if they don’t exist yet.

First, open NuGet Managet and install MongoDB.Driver package, which will install all the dependencies you need.

Let’s start with the domain. We will store a simple entity called SettingInfo which basically contains a Name and a Value:

[BsonIgnoreExtraElements] public class SettingInfo { [BsonId] [BsonRepresentation(BsonType.ObjectId)] //Allows you to not use the native MongoDB ObjectId public string Id { get; set; } [BsonElement(nameof(Name))] public string Name { get; set; } [BsonElement(nameof(Value))] public string Value { get; set; } [BsonRepresentation(BsonType.DateTime)] //Allows you to not use the native MongoDB DateTime [BsonElement(nameof(InsertedOnUtc))] public DateTime InsertedOnUtc { get; set; } [BsonRepresentation(BsonType.DateTime)] [BsonElement(nameof(UpdatedOnUtc))] public DateTime UpdatedOnUtc { get; set; } }
Code language: C# (cs)

Use the MongoDB attribute to simplify your life! Otherwise you will have to manage the BSON documents manually and it’s kind of a nightmare, trust me…

using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; namespace MongoDb_Demo { class Program { public static string Username => "YOU_USERNAME"; public static string Password => "YOUR_PASSWORD"; public static string ServerName => "YOUR_SERVER"; public static string Options => "IF_YOU_HAVE_SOME"; public static string DatabaseName => "MyMongoDB"; public static string CollectionName => "MyCollection"; public static string ConnectionString => $"mongodb+srv://{Username}:{Password}@{ServerName}{Options}"; static void Main(string[] args) { try { //Connect to MongoDb server MongoClient dbClient = new MongoClient(ConnectionString); //Get all databases List<string> dbList = dbClient.ListDatabaseNames().ToList(); //Get database IMongoDatabase database = dbClient.GetDatabase(DatabaseName); //Get Settings collection IMongoCollection<SettingInfo> settingsCollection = database.GetCollection<SettingInfo>(CollectionName); //Insert var settingName = "ThisIsMySetting"; var settingValue = "SettingValue"; var newSetting = new SettingInfo { Id = ObjectId.GenerateNewId().ToString(), Name = settingName, Value = settingValue, InsertedOnUtc = DateTime.UtcNow }; settingsCollection.InsertOne(newSetting); //Update newSetting.Value = "updatedValue"; newSetting.UpdatedOnUtc = DateTime.UtcNow; var updatedSetting = newSetting; settingsCollection.ReplaceOne(x => x.Id == newSetting.Id, updatedSetting); //Get specific document SettingInfo document = settingsCollection.Find<SettingInfo>(x => x.Name == settingName).FirstOrDefault(); //Get specific document by filter FilterDefinition<SettingInfo> filter = Builders<SettingInfo>.Filter.Eq(x => x.Name, settingName); SettingInfo filteredDocument = settingsCollection.Find<SettingInfo>(filter).FirstOrDefault(); //Get specific document by combined filters FilterDefinitionBuilder<SettingInfo> filterBuilder = Builders<SettingInfo>.Filter; FilterDefinition<SettingInfo> idFilter = filterBuilder.Where(x => x.Id == newSetting.Id); FilterDefinition<SettingInfo> nameFilter = filterBuilder.Where(x => x.Name == settingName); FilterDefinition<SettingInfo> combinedFilters = filterBuilder.And(idFilter, nameFilter); SettingInfo combinedFilteredDocument = settingsCollection.Find(combinedFilters).FirstOrDefault(); //Get all documents List<SettingInfo> allDocuments = settingsCollection.Find(new BsonDocument()).ToList(); //Delete settingsCollection.DeleteOne(x => x.Id == document.Id); } catch (Exception ex) { Console.WriteLine($"{ex.Message}"); } Console.WriteLine("Press any key to exist the program..."); Console.ReadKey(); } } }
Code language: C# (cs)

MongoDB is pretty simple to use and really flexible. I strongly recommend you to at least try it.