Create MongoDB Docker Image and Connect from .NET Core app

This blog creates a Docker MongoDB Image container, database, collection and connnect this container through .NET Core Console app to read table data.

Docker resolves a classic problem of developer it works on my machine!. You might have seen incidents where code is working absolutely fine on a developer machine however on a test or production environment it is not.

MongoDB is a NoSQL database, it is not the only SQL, it can do some different things than SQL databases. It stores data in JSON like documents.

  • Docker

    Docker Image

    Docker images are snapshots or blueprints of the original software or application. It is a collection of files that organize all required files to run the software. These files could be related to installations, application code, and dependencies, or configurations.

    Docker image can not be changed or modified, you can delete the existing image but can't change it. If you need a new version of the snapshot you will have to delete and create a new image.

    Docker Container

    Docker container is an instance of Docker image. Each container runs separately, unlike Docker Image, Docker container can be modified even when it is running. Containers can be created for Linux or Windows operating systems. Containers virtualize the operating system instead of hardware.

    The beauty of the Docker container is absolutely portable and works with any programing language. You build your container and use it anywhere in the absolute same manner where it was created.

    Docker Hub

    Docker hub is a repository registry service, using this repository you can search, pull Docler images or you can push your own image to the registry for use by other team members or public use. Docker hub images can be integrated with GitHub or BitBucket repositories.

    To pull any Docker Image you should have a valid account on Docker Hub. To create a Docker MongoDB container you need an account so go ahead and create an account using Docker Signup, if you don't have it.

    Docker Desktop

    Docker desktop helps to manage your applications, containers, images, MicroServices. Docker Desktop is available on Linux and Windows. You can download it from Docker Desktop.

    When you install Docker Desktop, all required assemblies for the Docker will be installed on your machine. Then you can use Docker through Terminal, Gitbash, Powershell.

  • What is MongoDB

    MongoDB is an open-source database that uses JSON-like documents data models and nonstructured query language. This database uses Key-Value pairs called BSON, it is a binary style of JSON documents. It is a NoSQL database meaning it does not use rows and columns.

    MongoDB provides drivers for many languages including C#, JAVA, NodeJS, for complete list visit - List of MongoDB drivers. In the next steps, we will use the MongoDB C# driver to connect its database and get data.

    MongoDB vs SQL

    • SQL database table will have fixed columns and rows whereas NoSQL database such as MongoDB is JSON documents, key-value pairs, dynamic columns.
    • SQL database will have rigid schema whereas MongoDB schema is flexible.
    • SQL database stored structured data whereas MongoDB stores unstructured data. MongoDB uses collection instead of tables and uses documents instead of rows.
    • SQL database is good for multi row transactions while MongoDB is better for documents, JSON data.
    • MongoDB provides better scalability than SQL databases.

  • Create MongoDB image

    You will have to create a MongoDB image before creating container or using it as an instance. In this step, you will download a MongoDB image to your Docker.

    Assuming you have installed Docker Desktop, open Gitbash or any terminal that you like and run a command.

    docker images

    This command shows the list of all images that are installed on local Docker. If MongoDB is not listed in the list then you can execute the following command to download the MongoDB images. This pulls Mongo library to your local docker.

    docker pull mongo

    Now if you execute docker images command you should see, Mongo image is installed as shown in the following diagram.

    docker image list

    By default, docker pull will pull the repository having the latest tag. If you want to pull a specific version you can use the following command. This will pull Mongo image having version 4.4.

    docker pull mongo:4.4
  • Create Instance of MongoDB as Container

    Now you will create a MongoDB container with the image that is available on your local machine. You can create / update databases using this container.

    The following command creates a container with the name geeksarray-mongo. Execute this command using GitBash or any other terminal.

    docker run -d -p 27017:27017 --name geeksarray-mongo mongo

    1. docker run: creates a container(instance) of the image and starts it.
    2. -d: run container in detached mode. This Means the docker container runs in the background of the terminal. It does not accept input or show output.
    3. -p 27017:27107: maps port 27017 of the container to port 27017 of the host. The syntax of the mapping port is -p HOST_PORT:CONTAINER_PORT.
    4. --name geeksarray-mongo: container name.
    5. mongo: image name.

    Execute this command to see the list of containers.

    docker ps

    Docker Container

    You can see the image and container list and their details using Docker Desktop.

    Now the container is running in the background however if you try to execute some command it will not run on the container. To execute commands on geeksarray-mongo container use the following command.

    docker exec -it geeksarray-mongo /bin/bash

    1. docker exec: runs the command on the container.
    2. -it: interactive terminal, whatever you type on the terminal will be passed to a container. Also, output from the container using STDOUT will be passed to the terminal.
    3. geeksarray-mongo: name of the container.
    4. /bin/bash: path.

    See the following image, commands are executed at the root of the container.

    docker exec command

    mongo shell is used for using mongo commands execute following command.

    mongo

    run mongo shell from docker

  • Create MongoDB database

    Now your MongoDB container with the name geeksarray-mongo is ready for creating a database. In this step, you will create a MongoDB database with the name GeeksArrayStore.

    To get a list of all databases.

    show databases

    To create and use a new database with the name GeeksArrayStore

    use GeeksArrayStore

    MongoDB create new Database

  • Create MongoDB Collection

    In this step, you will create a collection with the name Products to keep the products document. As MongoDB is a NoSQL database, there will not be tables with fixed numbers of columns.

    The following command creates a collection in GeeksArrayStore database. Notice there is no column definition.

    db.createCollection('Products')

    create mongodb database

    To see the list of all collections from GeeksArrayStore database.

    show collections

    Insert documents to collections

    InsertMany is used to insert one or multiple documents to the collection and returns _id value of each document. InsertMany is a feature of the MongoDB 3.2 version. You can also use InsertOne to insert a single document.

    The following code inserts an array of documents into the Product collection.

    db.Products.insertMany(
    [
    {
    	"Name": "Milton Thermosteel Flip Lid Flask",
    	"Category": "Kitchen & Dining",		
    	"Description": "Pre-condition bottle with hot water",
    	"Price": 54.93,
    	"Discount": "Yes",
    	"Image": "product001.png"
    },
    {
    	"Name": "Jabra Elite Active 75t True Wireless Active Noise Cancelling",
    	"Category": "Headphone",		
    	"Description": "Designed for secure fit and amazing durability.",
    	"Price": 88.93,
    	"Discount":"No",
    	"Image":"product002.png"
    }
    ])

    For a more detailed description of InsertMany visit - MongoDB collection InsertMany

    Get List of All Products documents

    If you want to get list of all products use the following command.

    db.Products.find({}).pretty()
    
  • Connect MongoDB Docker instance from .NET Core app

    Create a .NET Core console application using Visual Studio. You can go through for detailed steps to create a console app and using IConfiguration for app settings.

    Add Nugget package MongoDB.Driver for connecting MongoDB database.

    Add a class file with the name as Product.cs as Product Model. BSON serialization is used to convert MongoDB documents to C# object.

    
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    
    public class Product
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
    
        [BsonElement("Name")]
        public string Name { get; set; }
    
        [BsonElement("Category")]
        public string Category { get; set; }
        public string Description { get; set; }
        public string Image { get; set; }        
        public decimal Price { get; set; }
        public string Discount { get; set; }
    }
    

    Add a new class file with name ProductCollection.cs. This will initialize MongoClient, connect to the container, and get the Products document collection.

    using MongoDB.Driver;
    using System;
    using System.Collections.Generic;
    
    public class ProductCollection
    {
        public IMongoCollection<Product> Products { get; }
    
        public ProductCollection()
        {
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("GeeksArrayStore");
            Products = database.GetCollection<Product>("Products");
    
            //CatalogContextSeed.SeedData(Products);
    
            List list = Products.Find<Product>
                    (p => true).ToList<Product>();
    
            foreach(Product product in list)
            {
                Console.WriteLine($"ProductID: {product.Id} - Product Name: {product.Name}" );
            }
        }
    }
    

    Call this code from Program.cs

    static void Main(string[] args)
    {
        ProductCollection collection = new ProductCollection();
    
        Console.WriteLine("Hello World!");
    }
    

    This connects to container, get products collection and generates output as

    mongodb driver with dotnet core csharp

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!