Codementor Events

MongoDB C# Tutorial (The Easy Way)

Published May 23, 2019Last updated Feb 19, 2020
MongoDB C# Tutorial (The Easy Way)

the goal of this article is to familiarize you with an alternative, less verbose & convenient way to store and retrieve data in MongoDB server compared to what you'd typically see with such tutorials. hopefully by the end of this article you'll see the light and decide to ditch SQL Server & Entity Framework and get onboard the mongo train.

Install MongoDB server

if you don't already have mongodb server running on your machine, please follow this tutorial before moving forward.

Scaffold a console application project

create a new console application project using visual studio targetting .net core or enter the following in a powershell/cmd window:

dotnet new console -n LearnMongo
start .\LearnMongo\LearnMongo.csproj

Install Dependencies

open the package manager console and enter the following:
tip: tools > nuget package manager > package manager console

Install-Package MongoDB.Entities

Initialize Database Connection

open Program.cs file and make it look like the following:

using MongoDB.Entities;

namespace LearnMongo
{
    class Program
    {
        private static void Main(string[] args)
        {
            new DB("MyDatabase", "localhost", 27017);
        }
    }
}

we're specifying that this application should store our data in a database called MyDatabase in the mongodb server running on localhost listening on the default port.

Saving Entities

add a new class file called Person.cs to the project and make it look like the following:

using MongoDB.Entities.Core;
using System;

namespace LearnMongo
{
    class Person : Entity
    {
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
        public int SiblingCount { get; set; }
    }
}

main/root entities you want persisted to mongodb must inherit from the class Entity which is supplied by the package we installed earlier.

then go back to the Program.cs file and add the following below the db initialization line:

    var lisa = new Person {
        Name = "Lisa Malfrey",
        DateOfBirth = new DateTime(1983, 10, 11),
        SiblingCount = 1
    };

    lisa.Save();

    Console.WriteLine($ "Lisa's ID: {lisa.ID}");
    Console.Read();

now run the program by hitting ctrl+f5. you will see that the entity was saved and automatically assigned an ID.

note: the ID property comes from the base Entity class so that we don't have to keep adding it manually to each entity we create.

if you look inside the database using a db manager or mongo shell, you'll see that a collection called Person was created and a new record was added which looks like this:

{
    "_id": ObjectId("5e0c682ddd3765736cb8ca56"),
    "Name": "Lisa Malfrey",
    "DateOfBirth": ISODate("1983-10-10T18:30:00Z"),
    "SiblingCount": 1
}

Retrieving Entities

data can be retrieved in a couple of different ways. here are a few examples:

find by ID

    var result = DB.Find<Person>().One(lisa.ID);

    Console.WriteLine($ "Found Person: {result.Name}");
    Console.Read();

find by sibling count

    var result = DB.Find<Person>()
                   .Many(p => p.SiblingCount >= 1)
                   .First();

    Console.WriteLine($"Count: {result.SiblingCount}");
    Console.Read();

here we're saying find many Person entities who has at least 1 sibling. the .First() linq method simply picks the first person from the found list.

find by date range

    var result = DB.Queryable<Person>()
                   .Where(p => p.DateOfBirth > new DateTime(1983, 10, 10) &&
                               p.DateOfBirth < new DateTime(1983, 10, 12))
                   .First();

    Console.WriteLine($"Birthday: {result.DateOfBirth.ToLocalTime()}");
    Console.Read();

here we're using the IQueryable interface to retrieve the first person who has a date of birth that falls within the range of two dates.

Updating Entities

you can either retrieve the complete entity, update it's properties and save it back to the database or update certain properties of entities without retrieving them first.

update by retrieving complete entity

    var lisa = DB.Find<Person>().One(lisa.ID);

    lisa.Name = "Lisa Kudrow";
    lisa.SiblingCount = 2;

    lisa.Save();

update properties without retrieving

    DB.Update<Person>()
      .Match(p => p.ID == lisa.ID)
      .Modify(p => p.Name, "Lisa Kudrow")
      .Modify(p => p.SiblingCount, 2)
      .Execute();

Next Steps...

hope the above code has piqued your interest enough to go deeper into learning how to use mongodb with c# the easy way. the package MongoDB.Entities makes it extremely easy to communicate with mongodb server. every aspect of it's api has been documented in the wiki section of the package's github repository.

Discover and read more posts from Danny Roggers
get started
post commentsBe the first to share your opinion
Ajit Sanghera
4 years ago

Hi,

Can we get the source to download

Danny Roggers
4 years ago

the source is available on github

Show more replies