Use MongoDB in ASP.NET Core (Part - 1)

Now a days NoSQL databases are not uncommon. One such popular database is MongoDB. MongoDB is an open source and cross platform database that allows you to store data in the form of documents. This article series illustrates how MongoDB can be used in ASP.NET Core applications.

Brief introduction to MongoDB

I am not going into too much details of MongoDB in this article. You can read the official documentation here. Let me summarize some basics of MongoDB as follows :

  • MongoDB is an open source and cross platform NoSQL database.
  • MongoDB allows you to store data in the form of documents.
  • MongoDB documents are stored in JSON format.
  • A document holds the data in the form of key-value pairs. They are called fields.
  • A set of documents is called a collection. A collection can contain different types of documents.
  • A database can contain one or more collections.
  • When you add a new document to the database, by default MongoDB adds _id field to it that acts like a primary key. By default _id is set to an ObjectId but you can assign any other unique value to it.

Installing MongoDB on Windows

Ok. Now that you have basic idea of what MongoDB is let's see how you can install it on Windows. Go here and download either the MSI package or ZIP file containing the required files. Make sure to switch to the Server tab to find the required download.

In the above screenshot I am downloading the ZIP file of MongoDB Community Server version 4.0.4. After unpacking the ZIP file to a folder its contents are revealed as shown below :

Notice the two executables from the Bin folder. The Mongod.exe is the command line tool that allows you to connect with the MongoDB server. The Mongo.exe is a tool that acts as a client to the MongoDB server and you can use it to execute commands against the database such as CRUD operations.

Creating a MongoDB database

Now that we have the required software installed let's proceed to create a MongoDB database.

By default MongoDB stores database files under /data/db folder. But you can change this location as per your requirement. In our example we will store our files under \MongoDB_4.0.4\Data folder. So, create the Data folder under MongoDB_4.0.4 folder.

Next, open a command prompt and navigate to the MongoDB_4.0.4\Bin folder (the folder where Mongod.exe and Mongo.exe are located). Then issue the following command at the command prompt:

> mongod --dbpath ..\data

The above command attempts to connect with the MongoDB server and specifies dbpath command line parameter to the Data folder we created under MongoDB_4.0.4 earlier. The following figure shows a sample run of this command :

Now, let's create a new database called FirstDatabase. To do so, open another command prompt, navigate to the Bin folder as before, and issue the following command :

> mongo 

This command will start MongoDB client that you can use to issue further commands. The following figure shows a sample run of the above command :

Next, issue the following command in the MongoDB client command prompt :

> use FirstDatabase

The above command instructs the MongoDB to use the specified database. If the database already exists you will be switched to it, otherwise a new database with that name will be created for you.

Creating a MongoDB collection

As mentioned earlier MongoDB documents are stored in collections. For example, we will store our data in a collection named Employees. You can create the collection as follows :


The createCollection command will create a new collection with the specified name. Once created you can add documents to the collection.

CRUD operations using MongoDB client

Now that you created a new database - FirstDatabase - let's perform CRUD operations (Create, Read, Update, and Delete).

First of all, we will add some documents to the FirstDatabase. Let's assume that we want to store Employee information into our database - EmployeeID, FirstName, LastName, and Designation.

The following JSON markup shows how our Employee document might look like :

  EmployeeID : 1,
  FirstName : "Nancy",
  LastName : "Davolio",
  Designation : "Sales manager"

Inserting data

How do you add this document to the FirstDatabase? Simply issue the following command at the MongoDB client command prompt :

> db.Employees.insert({{EmployeeID : 1,
  FirstName : "Nancy",
  LastName : "Davolio",
  Designation : "Sales manager"} })

Here, Employees is developer defined collection name (we created it in the preceding section). We add a new document to the Employees collection using the insert command.

Add a few more employee documents using the same command so that we can perform the remaining operations.

Reading data

Ok. Before updating or deleting data let's try to fetch Employee documents we just stored. Issue the following command :

> db.Employees.find()

The find command will retrieve all the documents from the Employees collection and they will be outputted on the console. For example, see the following output :

{ "_id" : ObjectId("5bf37c94cfaa07a8454b3fb8"), 
  "EmployeeID" : 1, 
  "FirstName" : "Nancy", 
  "LastName" : "Davolio", 
  "Designation" : "Sales manager" }

Did you notice that an additional field - _id - has been automatically added for you in the document? This is done by MongoDB server for you and _id acts like a primary key. By default the value of _id is what is known as an ObjectId but you can use any unique value. For example, you can store the EmployeeID as the value of _id. In that case your insert command will look like this :

> db.Employees.insert({{_id : 1,
  FirstName : "Nancy",
  LastName : "Davolio",
  Designation : "Sales manager"} })

Now, MongoDB won't assign ObjectId to the _id field, instead it will use the value you specified.

Updating data

Now, let's update employee document. Issue the following command :

> db.Employees.update({EmployeeID : 1},
  {$set:{Designation : "Sales Executive"}})

The update command takes two parameters :

  • The first parameter is a criteria that decides which document(s) is to be modified.
  • The second parameter specifies the modified fields.

In the preceding example, look for a document whose EmployeeID field is 1 and then we change its Designation field to Sales Executive.

You can specify multiple fields in the first parameter if required. The second parameter need not include all the fields, just the modified fields are sufficient. This is the job of $set operator. If you skip the $set operator the whole document will be replaced by the document specified in the second parameter.

Just to confirm that update has really happened, issue the find() command as before. You should see the new designation outputted on the console. 

Deleting data

Now let's remove the data from Employees collection. Issue the following command :


The remove command accepts criteria for removing data and removes the matching document(s). In the above example we delete an employee document whose EmployeeID field is 1. As before confirm whether the data has been really deleted or not by issuing find() command.

If you wish to remove all the documents you can issue the following command:


As you can see specifying an empty criteria removes all the documents from the Employees collection.

That's it for now! In the next part of this series I will explain how to connect to MongoDB from ASP.NET Core application. Till then keep coding!!

Bipin Joshi is an independent software consultant, trainer, author, and meditation teacher. He has been programming, meditating, and teaching for 25+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 26 November 2018

Tags : ASP.NET ASP.NET Core Data Access MVC Visual Studio