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:
A NoSQL (originally referring to “non SQL” or “non relational”)[1] database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases. 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] triggered by the needs of Web 2.0 companies.[3][4][5]NoSQL databases are increasingly used in big data and real-time web applications.[6] NoSQL systems are also sometimes called “Not only SQL” to emphasize that they may support SQL-like query languages, or sit alongside SQL database in a 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
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) using the command:
dotnet new console -n Kritner.MongoDb.GettingStarted.ConsoleApp
MongoDB.Driver NuGet Package
Next we’ll need a NuGet package that will allow us to work with MongoDb easily:
The Code
Now all that is left is to write a bit of c# code to try out MongoDb!
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):
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:
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:
Top comments (1)
Thanks for this. It was a good intro into Mongo.