Click here to Skip to main content
15,868,056 members
Articles / Database Development / MongoDB

Kickstart with .NET Core and MongoDB - Console App

Rate me:
Please Sign up or sign in to vote.
4.47/5 (7 votes)
19 Jan 2017CPOL3 min read 9.8K   110   5   2
In this article, you will learn how to create console application in .NET Core with NoSQL- MongoDB.

Introduction

I am going to demonstrate how to create a very simple .NET Core Application using NoSQL - MongoDB with C# official driver version 2.4. I assume, you have a little understanding about .NET framework connectivity.

Prerequisite

  1. To work with the application, you need to have Visual Studio 2015 with update 3, in order to have .NET Core (It is my motivation to show you a utility with .NET Core but you can proceed with any version of Visual Studio).
     
  2. You will have to install NoSQL Database Server MongoDB. You can find it here.
     
  3. This step is not mandatory but it will be good to have GUI friendly application to manage MongoDB Server. One among many tools you can download and install is Mongobooster [https://mongobooster.com/] -> download. Otherwise, you can also work from the command prompt. I will use parts of both.

Demonstration

 

You can complete this step by step application in 8 steps. I tried to answer some of the debugging stages in the process. Still, if you find any difficulty, please post in comments section.

  1. Create a folder named 'data' in C: drive and 'db' within 'data' folder. This will be keeping your database. e.g. - C:\data
     
  2. Now, you have to start the MongoDb instance. To do this, go to C:\Program Files\MongoDB\Server\3.2\bin (I assume that you have installed  or just downloaded MongoDb default instance). Open its bin in command prompt, e.g cd C:\Program   Files\MongoDB\Server\3.2\bin. If you have version 3.4, your path will be e.g cd C:\Program Files\MongoDB\Server\3.4\bin and so. 

    Now, execute mongod.exe with parameter --dbpath. Example - C:\Program Files\MongoDB\Server\3.2\bin>mongod.exe --dbpath C:\data\db



    Note: You can also create a Windows Service for the above job to make your life easy next time.
     
  3. By now, your MongoDB Server is up and running. Don't close this command prompt till end. Open your Mongobooster and go to create and connection. Mongobooster --> Connect --> Create --> (With all default connect port 27017) --> Save and Connect. 

    Great ! You are connected with Mongo Server now.
     
  4. Right click on localhost (Server on left panel) and create a database named 'School'. Then, right click on School database and create Collection. This collection is nothing but your table in RDBMS. Just name it as 'StudentDetails'. Here, a book can be written on Collection, Document, BSON. To check if everything is on track, right click on StudentDetails and select to view document. Don't worry, you will find no records but query in the window. 
     
  5. Now, we are ready with back-end, so come to Visual Studio -> File -> New -> Project -> Console Application (select .NET Core but optional) -> Create.
     
  6. Right click on reference to get NuGet Package Manager to get the driver to get connectivity with MongoDB. In "Browse", search for MongoDB.Driver driver and install it. For this example, I am using version 2.4.


     
  7. Replace the below code with that in your Program.cs file. 
C++
using System;

//MongoDB.Driver
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization;

namespace AppTest
{
    public class ProfileIdGenerator : IIdGenerator
    {
        public object GenerateId(object container, object document)
        {
            return "Test-"+ Guid.NewGuid().ToString();
        }

        public bool IsEmpty(object id)
        {
            return id == null || String.IsNullOrEmpty(id.ToString());
        }
    }

    public class Students
    {
        [BsonId(IdGenerator = typeof(ProfileIdGenerator))]
        public string ProfileId { get; set; }

        //[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
        //public string ProfileId { get; set; }

        //[BsonId]
        //public ObjectId ProfileId { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string Age { get; set; }
    }

    public class Program
    {
        protected static IMongoClient _client;
        protected static IMongoDatabase _database;

        public static Students GetStudent()
        {
            Console.WriteLine("Please enter student first name : ");
            string FNm = Console.ReadLine();

            Console.WriteLine("Please enter student last name : ");
            string LNm = Console.ReadLine();

            Console.WriteLine("Please enter student age : ");
            string StudentAge = Console.ReadLine();

            Console.WriteLine("Please enter city name : ");
            string StudentCity = Console.ReadLine();

            Students student = new Students()
            {
                FirstName = FNm,
                LastName = LNm,
                Age = StudentAge,
                City = StudentCity,
            };

            return student;
        }

        public void CRUDwithMongoDb()
        {
            _client = new MongoClient();
            _database = _client.GetDatabase("School");
            var _collection = _database.GetCollection<Students>("StudentDetails");

            Console.WriteLine
                ("Press select your option from the following\n1 - Insert\n2 - Update One Document\n3 - Delete\n4 - Read All\n");
            string userSelection = Console.ReadLine();

            switch (userSelection)
            {
                case "1": 
                    //Insert
                    _collection.InsertOne(GetStudent());
                    break;

                case "2": 
                    //Update
                    var obj1 = GetStudent();

                    _collection.FindOneAndUpdate<Students>
                        (Builders<Students>.Filter.Eq("FirstName", obj1.FirstName),
                            Builders<Students>.Update.Set("LastName", obj1.LastName).Set("City", obj1.City).Set("Age", obj1.Age));
                    break;

                case "3": 
                    //Find and Delete
                    Console.WriteLine("Please Enter the first name to delete the record(so called document) : ");
                    var deletefirstName = Console.ReadLine();
                    _collection.DeleteOne(s => s.FirstName == deletefirstName);

                    break;

                case "4": 
                    //Read all existing document
                    var all = _collection.Find(new BsonDocument());
                    Console.WriteLine();

                    foreach (var i in all.ToEnumerable())
                    {
                        Console.WriteLine(i.ProfileId + "  " + i.FirstName + "\t" + i.LastName + "\t" + i.Age + "\t" + i.City);
                    }

                    break;

                default:
                    Console.WriteLine("Please choose a correct option");
                    break;
            }

            //To continue with Program
            Console.WriteLine("\n--------------------------------------------------------------\nPress Y for continue...\n");
            string userChoice = Console.ReadLine();

            if (userChoice == "Y" || userChoice == "y")
            {
                this.CRUDwithMongoDb();
            }
        }

        public static void Main(string[] args)
        {
            Program p = new Program();
            p.CRUDwithMongoDb();

            
            //Hold the screen by logic
            Console.WriteLine("Press any key to trminated the program");
            Console.ReadKey();
        }
    }
}

       8. Just run (Crl + F5) the console application.

 

Conclusion

In this application, I have demonstrated CRUD operation with .NET Core and MongoDB. Demonstrated project is available with the name of AppTest.rar, attached with this article. Additionally, you can learn about customization of BsonDocument to our own format on my blog here. NoSQL can have a different number of columns (fields) in different rows (called document). ID can also be customized instead of FirstName but for this example, I took one quite simple application. CustomizedProject zip is available also, that I have discussed on my blog.

If you like this work, please rate it highly, like/share the post, and subscribe to my profile for more updates. Thanks!

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am an passionate technology evangelist. I like reading and talks on technology you can join me on twitter or join my small group on WhatsApp for technology activities https://chat.whatsapp.com/F9LLSJVwKiT8GIOaSXb7u5

Comments and Discussions

 
Questioncan you please attach zips, not rar?! Pin
Roman Ivantsov23-Jan-17 8:56
professionalRoman Ivantsov23-Jan-17 8:56 
AnswerRe: can you please attach zips, not rar?! Pin
AHMAD ANAS23-Jan-17 18:27
AHMAD ANAS23-Jan-17 18:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.