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.
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:
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:
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.
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. you can also check out the source code on github:
A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management
MongoDB.Entities
A light-weight .net standard library with barely any overhead that aims to simplify access to mongodb by abstracting the official driver while adding useful features on top of it resulting in an elegant API surface which produces beautiful, human friendly data access code.
More Info:
please visit the official website for detailed documentation: