Create C# .Net Application Using Mongo Database

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.

using MongoDB.Driver;
using MongoDB.Bson;
class Program
{
    static void Main(string[] args)
    {
        // Connection string and database name
        string connectionString = "mongodb://localhost:27017";
        string dbName = "mydatabase";
        // Create a MongoDB client
        MongoClient client = new MongoClient(connectionString);
        // Get a reference to the database
        IMongoDatabase database = client.GetDatabase(dbName);
        // Access a collection
        IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("mycollection");
        // Insert a document
        BsonDocument document = new BsonDocument
        {
            { "name", "John" },
            { "age", 30 }
        };
        collection.InsertOne(document);
        // Query the collection
        var result = collection.Find(new BsonDocument("name", "John")).ToList();
        foreach (var doc in result)
        {
            Console.WriteLine(doc.ToJson());
        }
    }
}

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.

var mongo = new Mongo();
mongo.Connect();
var db = mongo.getDB("testmongo");

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.

var mongo = new Mongo();
mongo.Connect();
// Create or access a database named "testmongo" under the "c:\Data\db" folder.
var db = mongo.getDB("testmongo");

Now write the following code.

var categorylist = db.GetCollection("studcategories");
var category = new Document();
category["Name"] = "shirsendu nandi";
category["Id"] = "20";
category["Address"] = "bangalore";
categorylist.Insert(category);
Console.WriteLine("Total number of data is: " + categorylist.Count());

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

category["Name"] = "shirsendu Nandi";

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.

categorylist.Insert(category);

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.

var categories = db.GetCollection("studcategories").FindAll().Documents;
foreach (var lstcategory in categories)
{
    Console.WriteLine(lstcategory["Name"]);
    Console.WriteLine(lstcategory["Id"]);
    Console.WriteLine(lstcategory["Address"]);
}

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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Driver.Bson;
namespace mongodbconsoleapplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var mongo = new Mongo();
            mongo.Connect();
            var db = mongo.getDB("testmongo");
            var categorylist = db.GetCollection("subcategories");
            var category = new Document();
            category["Name"] = "shirsendu nandi";
            category["Id"] = "20";
            category["Adress"] = "bangalore";
            categorylist.Insert(category);
            Console.WriteLine("Total number of data is: " + categorylist.Count());
            var categories = db.GetCollection("studcategories").FindAll().Documents;
            foreach (var lstcategory in categories)
            {
                Console.WriteLine(lstcategory["Name"]);
                Console.WriteLine(lstcategory["Id"]);
                Console.WriteLine(lstcategory["Adress"]);
            }
            Console.ReadLine();
        }
    }
}

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.


Similar Articles