Breaking

Wednesday, September 20, 2017

Step by step instructions to work with MongoDB in .Net

Begin with records and accumulations in the well known, open source, NoSQL database utilizing C#




MongoDB is a well-known, open source, scale-out NoSQL database that gives high throughput to your information-driven applications. Dissimilar to social databases, for example, SQL Server, Oracle, and MySQL, which store information in tables as indicated by an unbending construction, MongoDB stores information in records with the adaptable pattern. There are numerous such non-social databases around including CouchDB, RavenDB, and Couchbase. Be that as it may, I like MongoDB fundamentally because of its versatility, speed, and dynamic questioning abilities. 

MongoDB utilizes the BSON organize in the engine to speak to the JSON reports at the core of the information store. BSON or "Parallel JSON" is a lightweight and productive double encoded information serialization arrange that backings quick information traversal and inquiries. BSON additionally enables MongoDB to help information sorts—specifically int, long, date, gliding point, and decimal128—not spoke to in JSON. 

In MongoDB, reports are a piece of accumulations, similarly as a line is a piece of a table in a social database. A record is basically an accumulation of field and esteem sets, which can likewise be settled. Note that an incentive in MongoDB can be a record, a variety of reports, a variety of BSON, or only a BSON sort. We should take a gander at how we can function with MongoDB utilizing C#. 

Introduce MongoDB and make another task 

Begin by downloading the MongoDB pairs. Unfasten your preferred parallels to an organizer in your framework and make a different envelope (for my situation C:\data\db) for the information. At that point, to begin MongoDB, explore to the envelope where MongoDB is introduced and execute the mongod order in the charge provoke window. That should begin MongoDB at port 27017 as a matter of course. 

Make another support application venture in Visual Studio and introduce the MongoDB.Driver bundle through the NuGet Package Manager Console with the accompanying summon. 

PM> Install-Package MongoDB.Driver

This will introduce the accompanying three NuGet bundles at one go. 

MongoDB.Bson 

MongoDB.Driver.Core 

MongoDB.Driver 

Interface with your MongoDB case 

To interface with a MongoDB case at its default port 27017, you can utilize the default constructor of the MongoClient class as demonstrated as follows. 

var client = new MongoClient();

Presently consider the accompanying class. We will utilize this class to store information in MongoDB. 

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
Make a database and gathering 

The accompanying code posting indicates how you can make a database and a gathering inside it and afterward embed a protest inside the accumulation. 

static void Main(string[] args)
    {           
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);           
        IMongoDatabase db = client.GetDatabase(“IDG”);
        Author author = new Author
        {
            Id = 1,
            FirstName ="Joydip",
            LastName ="Kanjilal"
        };
        var collection = db.GetCollection<Author>(“authors”);
        collection.InsertOne(author);
        Console.Read();
    }
Note that the accompanying namespaces ought to be incorporated into your program. 

using MongoDB.Bson;
using MongoDB.Driver;

Presently allude to the Main technique in the code posting above. Note that the accompanying articulation makes new a database named "IDG" if none exists by that name. 

IMongoDatabase db = client.GetDatabase(“IDG”);

Additionally, the accompanying articulation makes another gathering of "Creator" objects if none exists. In either case, the GetCollection technique restores an accumulation occurrence. 

var collection = db.GetCollection<Author>(“authors”);

Add records to the accumulation 

Next, we make an occurrence of the Author class and allocate esteems to its FirstName and LastName properties. 

Author author = new Author
{
    Id = 1,
    FirstName ="Joydip",
    LastName ="Kanjilal"
};

Utilize the announcement underneath to embed the example of the Author class into the accumulation. 

collection.InsertOne(author);

Note that you can embed numerous reports all in the meantime utilizing the InsertMany or InsertManyAsync technique. The accompanying code posting represents how the InsertMany technique can be utilized. 

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;

static void Main(string[] args)
    {           
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);           
        IMongoDatabase db = client.GetDatabase(“IDG”);
        var collection = db.GetCollection<BsonDocument>(“IDGAuthors”);
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;

static void Main(string[] args)
    {           
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);           
        IMongoDatabase db = client.GetDatabase(“IDG”);
        var collection = db.GetCollection<BsonDocument>(“IDGAuthors”);
        var author1 = new BsonDocument
        {
            {”id”, 1},
            {”firstname”, Joydip”},
            {”lastname”, Kanjilal”}
        };
        var author2 = new BsonDocument
        {
            {”id”, 2},
            {”firstname”, Steve”},
            {”lastname”, Smith”}
        };
        var author3 = new BsonDocument
        {
            {”id”, 3},
            {”firstname”, Gary”},
            {”lastname”, Stevens”}
        };
        var authors = new List<BsonDocument>();
        authors.Add(author1);
        authors.Add(author2);
        authors.Add(author3);
        collection.InsertMany(authors);
        Console.Read();
    }

The BsonDocument class in the MongoDB.Bson bundle is utilized to speak to a BSON archive. The accompanying code scrap demonstrates how you can show the names of the databases accessible in the case of MongoDB running in your framework. 

var connectionString ="mongodb://localhost:27017";
var client = new MongoClient(connectionString);           
    using (var cursor = client.ListDatabases())
    {
        var databaseDocuments = cursor.ToList();
        foreach (var db in databaseDocuments)
        {
            Console.WriteLine(db[“name”].ToString());
        }
    }

When you execute the above code piece, you will see the name of the database (i.e., "IDG") recorded in the reassure window. You can likewise utilize the offbeat strategy, ListDatabasesAsync, to list the database names, as appeared in the code bit given beneath. 

private static async Task DisplayDatabaseNames()
    {
        var connectionString ="mongodb://localhost:27017";
        var client = new MongoClient(connectionString);
        try
        {
            using (var cursor = await client.ListDatabasesAsync())
            {
                await cursor.ForEachAsync(document => Console.WriteLine(document.ToString()));
            }               
        }
        catch
        {
            //Write your own code here to handle exceptions
        }
    }
MongoDB is a prevalent NoSQL database that has an adaptable information model and scales nimbly. MongoDB offers help for level adaptability utilizing a strategy known as sharding. I will examine further developed ideas in MongoDB in future posts here. Until at that point, you might need to peruse up on the MongoDB C# driver in the MongoDB documentation.



No comments:

Post a Comment