Tutorial: MongoDB With C# The Easy Way!
Đĵ ΝιΓΞΗΛψΚ
Updated on
・3 min read
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.
How To Install MongoDB Server On Windows & Linux
Đĵ ΝιΓΞΗΛψΚ ・ Dec 30 '19 ・ 3 min read
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 which you can find below:
dj-nitehawk
/
MongoDB.Entities
A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management
MongoDB.Entities
This library simplifies access to mongodb by abstracting away the C# mongodb driver and providing some additional features on top of it. The API is clean and intuitive resulting in less lines of code that is more readable/ human friendly than driver code.
Advantages:
- Never have to deal with
ObjectIds,
BsonDocuments& magic strings.
- Built-in support for
One-To-One,
One-To-Manyand
Many-To-Manyrelationships.
- Query data using LINQ, lambda expressions, filters and fluent aggregations.
- Sorting, paging and projecting is made convenient.
- Simple data migration framework similar to EntityFramework.
- Programatically define indexes.
- Full text search (including fuzzy matching) with text indexes.
- Multi-document transaction support.
- Easy bulk operations.
- Update with aggregation pipeline stages & array filters.
- Easy GeoSpatial search.
- Stream files in chunks to and from mongodb (GridFS alternative).
- Multiple database support.
- Project types supported: .Net Standard 2.0 (.Net Core 2.0 or higher & .Net Framework 4.6.1 or higher)
Documentation
What do you have to Google? Every. Single. Time.
How about you? Any other stories to make me feel better?
