Introduction
To know what a MongoDB is, how to install it, and how to install the C# MongoDB driver, please see the article "Mongo database in .Net with C#.
Now, we are creating the sample application.
Step 1. Create a console application named "MongodbConsole" Application.
Now write the following code under the namespace area.
MongoDB.Driver is the C# driver for using the MongoDB database in a C# .Net application.
Step 2. Now go to the "bin" folder under the "mongodb-win32-i386-1.8.1" folder. After that, click the "mongod" exe, just like in Figure 1. It is the server for the MongoDB. You must open the MongoDB database server while you are creating an application using MongoDB. We can open the MongoDB database server by using the Windows service also.
![mon.gif]()
Figure.1
Now we have to first connect to the database. So under the void main, we will write the code.
Here we are creating the object variable of the "Mongo" database. Then we are going to open the connection of the database by writing "mongo. Connect();". It is the same as "con. open()" for ADO.Net programming.
Now write the following code.
db.GetCollection ("subcategories");" means it will create a collection name "subcategories" under the "testmongo" database.
After that, we create the variable of the document (e.g.: table in SQL server).
Now we are assigning the the variable with name, ID, and age.
Example
Here, the "Name" is the key value of the document, and the "category ["Name"]" is the field.
You can consider that to be like a "Dictionary" or "Hashtable" in .Net collection classes.
Now we are saving the category value in the mongo database by writing this code.
We also get the total count of the records using "categorylist. Count ());"
Now press F5. Your record has been stored in the mongo db. To see that go to the "c:\Data\db" folder. You will see "testmongo. ns" has been created just like Figure 2 (marked with red). By default, the size of the database will be 16MB. It will increase automatically according to the data. But for 32-bit Windows, the maximum memory capacity will be 2 GB.
![mon1.gif]()
Figure.2
Step 3. Now we have to retrieve the data from the "subcategories" and display it.
For that, we have to write the code shown below.
Here first, we find all the records from the documents of "subcategories" by using "FindAll(). Documents;".
After that, we loop through each "category" and display the records.
So the complete code is.
Now run the application; it will look like the figure shown below.
![output]()
Conclusion
So in this article, I have described how to save and fetch data from a mongo db using C# .NET.