Getting started on MongoDb with .NET Core
Tags: softwaredevelopment, softwareengineering, programming, nosql
Published: 2019-03-13 16:06:50

---
title: Getting started on MongoDb with .NET Core
published: true
tags: software-development,software-engineering,programming,nosql
canonical_url: https://medium.com/@kritner/getting-started-on-mongodb-with-net-core-89022de0ca29
image_url: https://cdn-images-1.medium.com/max/1024/0*liuKb58RDVblR0WC
---

### Getting started on MongoDb with .NET Core

<figcaption>Photo by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>

Coming from a strictly relational db world, NoSql style databases have always seemed a bit scary! I recently had the opportunity to play around with MongoDb for the first time, and I was quite surprised by how easy it was to get started!

### What is a NoSql database?

From [wikipedia](https://en.wikipedia.org/wiki/NoSQL):

> A **NoSQL** (originally referring to “non [SQL](https://en.wikipedia.org/wiki/SQL)” or “non relational”)[[1]](https://en.wikipedia.org/wiki/NoSQL#cite_note-1) [database](https://en.wikipedia.org/wiki/Database) provides a mechanism for [storage](https://en.wikipedia.org/wiki/Computer_data_storage) and [retrieval](https://en.wikipedia.org/wiki/Data_retrieval) of data that is modeled in means other than the tabular relations used in [relational databases](https://en.wikipedia.org/wiki/Relational_database). Such databases have existed since the late 1960s, but did not obtain the “NoSQL” moniker until a surge of popularity in the early 21st century,[[2]](https://en.wikipedia.org/wiki/NoSQL#cite_note-leavitt-2) triggered by the needs of [Web 2.0](https://en.wikipedia.org/wiki/Web_2.0) companies.[[3]](https://en.wikipedia.org/wiki/NoSQL#cite_note-3)[[4]](https://en.wikipedia.org/wiki/NoSQL#cite_note-4)[[5]](https://en.wikipedia.org/wiki/NoSQL#cite_note-5)NoSQL databases are increasingly used in [big data](https://en.wikipedia.org/wiki/Big_data) and [real-time web](https://en.wikipedia.org/wiki/Real-time_web) applications.[[6]](https://en.wikipedia.org/wiki/NoSQL#cite_note-6) NoSQL systems are also sometimes called “Not only SQL” to emphasize that they may support [SQL](https://en.wikipedia.org/wiki/SQL)-like query languages, or sit alongside SQL database in a [polyglot persistence](https://en.wikipedia.org/wiki/Polyglot_persistence) architecture.

Traditionally with relational databases you strive for as normalized of data as possible; tables with foreign key relationships more or less. With a NoSql database, it seems like doing a lot of that “design” around keeping your data structure is not as necessary — in a lot of situations you can simply get away with storing the entirety of the object in a single document.

### Why MongoDb?

Honestly, I don’t know much at all about NoSql style databases. I knew I had a potentially massive amount of varying “schema” json objects that I needed to store, and I needed to figure out a way to do it quickly. MongoDb is something I’ve heard of, as well as a few others that were thrown out: Cassandra, Raven, Redis, Couch, etc. A few of these were out of reach immediately, as it seemed that they were only available on linux — at least at a cursory look. Others it was difficult to find information or packages that would interface with .net core. MongoDb luckily has a community addition, installs on windows, and a .net standard based NuGet package that can be used with .net core — sold!

### Installation

A straightforward tutorial on getting MongoDb up and running on Windows, as a service (or not) can be found here:

[Install MongoDB Community Edition on Windows - MongoDB Manual](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/)

### Sample code for .net core

So now that that the database is installed, we can now proceed onto the traditional hello world application when poking around something new!

#### New application

Let’s start a new application with .net core (SDK found [here](https://dotnet.microsoft.com/download)) using the command:

```
dotnet new console -n Kritner.MongoDb.GettingStarted.ConsoleApp
```

![](https://cdn-images-1.medium.com/max/1024/1*T8fD_hg_1lAfWysuo0a_Tw.png)

#### MongoDB.Driver NuGet Package

Next we’ll need a NuGet package that will allow us to work with MongoDb easily:

[MongoDB.Driver 2.7.3](https://www.nuget.org/packages/MongoDB.Driver/)

#### The Code

Now all that is left is to write a bit of c# code to try out MongoDb!

```cs
public class MyHelloWorldMongoThing
{
 public DateTime DateCreated { get; set; } = DateTime.Now;
 public string MyDatas { get; set; }
}

class Program
{
 static void Main(string[] args)
 {
  Console.WriteLine("What would you like to enter for MyDatas?");

  // Get some input from user
  var myDatas = Console.ReadLine();

  // Create an object with the data that was entered
  var obj = new MyHelloWorldMongoThing()
  {
   MyDatas = myDatas
  };

  // get a mongoclient using the default connection string
  var mongo = new MongoClient();

  // get (and create if doesn't exist) a database from the mongoclient
  var db = mongo.GetDatabase("MyHelloWorldDb");

  // get a collection of MyHelloWorldMongoThings (and create if it doesn't exist)
  // Using an empty filter so that everything is considered in the filter.
  var collection = db.GetCollection<MyHelloWorldMongoThing>("myHelloWorldCollection");

  // Count the items in the collection prior to insert
  var count = collection.CountDocuments(new 
FilterDefinitionBuilder<MyHelloWorldMongoThing>().Empty);
  Console.WriteLine($"Number of items in the collection after insert: {count}");

  // Add the entered item to the collection
  collection.InsertOne(obj);

  // Count the items in the collection post insert
  count = collection.CountDocuments(new FilterDefinitionBuilder<MyHelloWorldMongoThing>().Empty);
 Console.WriteLine($"Number of items in the collection after insert: {count}");
 }
}
```

It could look like this when running (note I've run this a few times, and since it’s persisted data, the counts are incrementing each run):

![](https://cdn-images-1.medium.com/max/1024/1*3R5G7zcpF0uP-S_xwOlFIg.png)

#### Review the Created Data

Now that we’ve inserted data, we can query that data using c#, or take a look at it with some of the mongo tools that came with the installation — like the mongo shell or compass.

Here’s a sample of what the data can look like from compass:

![](https://cdn-images-1.medium.com/max/1024/1*56zln-22P9AnKZLYa-gSkw.png)

From the above you can see the documents we’ve inserted via the console application are present, and that they exist in a database and collection that was created automatically via the code.

### Wrapping Up

Hopefully the above helps show that it’s quite simple to get started playing around with MongoDb. Note that the above does not look at any security related concerns, so make sure to take that into account if you’re moving forward with MongoDb.

I’ve been working with a relational database for so long that NoSql seemed pretty intimidating, but getting started with it was a lot easier than I expected!

Code for the following post can be found at:

[Kritner-Blogs/Kritner.MongoDb.GettingStarted](https://github.com/Kritner-Blogs/Kritner.MongoDb.GettingStarted/releases/tag/v.01)