Tutorial: MongoDB With C# The Easy Way!
Tags: mongodb, dotnet, csharp, tutorial
Published: 2020-01-01 11:31:03

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 the tutorial below before moving forward.

{% link /djnitehawk/how-to-install-mongodb-server-on-windows-linux-4in %}

# 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:
```csharp
using MongoDB.Entities;
using System.Threading.Tasks;

namespace LearnMongo
{
    static class Program
    {
        private async static Task Main()
        {
            await DB.InitAsync("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:

```csharp
using MongoDB.Entities;
using System;

namespace LearnMongo
{
    public 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:

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

await lisa.SaveAsync();

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:
```javascript
{
    "_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
```csharp
var result = await DB.Find<Person>().OneAsync(lisa.ID);

Console.WriteLine($"Found Person: {result.Name}");
Console.Read();
```
### find by sibling count
```csharp
var result = (await DB.Find<Person>()
                      .ManyAsync(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
```csharp
var result = await DB.Queryable<Person>()
                     .Where(p => p.DateOfBirth > new DateTime(1983, 10, 10) &&
                                 p.DateOfBirth < new DateTime(1983, 10, 12))
                     .FirstOrDefaultAsync();

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
```csharp
var person = await DB.Find<Person>().OneAsync(lisa.ID);

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

await person.SaveAsync();
```

### update properties without retrieving

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

# 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 on the [official website](https://mongodb-entities.com). you can also check out the source code on github:
{% github dj-nitehawk/MongoDB.Entities %}