• September 21, 2017 10:13 am
  • by Aruthra

ASP.Net Web API with MongoDB

  • September 21, 2017 10:13 am
  • by Aruthra

According to Wikipedia “MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. ” So MongoDB is a non-relational database and the terminologies used in this are different compared to relational databases like MSSQL.

Relattional Database MongoDB
Database Database
Table Collection
Row Document
Column Field

I will start by installing MongoDB into the machine. Install it and once the installation is over, the system drive will create a MongoDB folder in the following path C:\Program Files\MongoDB. At the time of writing, the latest stable release is 3.4.4. If you go into the bin folder (C:\Program Files\MongoDB\Server\3.4\bin) you can see a bunch of executables.

Mongod.exe, the third one from the top is the mongo server and mongo.exe is the shell. We will use the shell to connect to the server and perform some operations. Before that we have to make sure that the server is up and running. The rest of the executable files are used for backup and restore, import and export, monitor server etc.

Before going to run the mongo server for the first time you would need to create a directory where the data files reside. The default name for the directory is data\db. Run the following command to create a new directory under C drive

Once that directory exists, you can simply run the mongo server with the keyword “mongod”

If we look into the details displayed in the command prompt you can see that MongoDB has been started, initialize data in directory and up and running at port number 27017 and it is ready to use. We can shut it down cleanly by entering Ctrl+C.

Next thing I’m going to do is to integrate MongoDB into a Web API project. For an application like web api to communicate with MongoDB, is possible only by the use of a client library called driver. MongoDB provides a set of drivers which supports different programming languages and I’m going to use the C# Driver.

Step:1 – Create a new web api project.

Step:2 – Install MongoDB C# driver into the application. Browse “mongodb.driver” in NuGet window and install it. It is the official .NET driver for MongoDB.

Step:3 – I’m going to create a new database called VofoxDB and save employee details in a collection called ‘Employees’. I have created a model class ‘Employee’ and added some properties. The model contains an Id property which will map to the _id field of the document in database. MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while creating any document. By providing the BsonId and BsonType attributes, I have declared Id property as a string and when MongoDB serializes it, it’s internally treated as an ObjectId.

 public class Employee
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Email { get; set; }
        public string Designation { get; set; }
    }

Step 4 – The data access layer contains the set of CRUD operations to manipulate the Employee collection.

public class EmployeeRepository
    {
        protected static IMongoClient _client;
        protected static IMongoDatabase _database;
        protected static IMongoCollection<Employee> _collection;
        public EmployeeRepository()
        {
            _client = new MongoClient("mongodb://localhost:27017");
            _database = _client.GetDatabase("VofoxDB");
            _collection = _database.GetCollection<Employee>("Employees");
        }
        public async Task<IEnumerable<Employee>> GetAllEmployees()
        {
            var filter = new BsonDocument();
            var result = await _collection.Find(filter).ToListAsync();
            return result;
        }
        public async Task<Employee> GetEmployee(Object id)
        {
            var filter = Builders<Employee>.Filter.Eq(e => e.Id, id);
            var result = await _collection.Find(filter).FirstOrDefaultAsync();
            return result;
        }
        public async Task CreateEmployee(Employee employee)
        {
            await _collection.InsertOneAsync(new Employee
            {
                EmployeeId = employee.EmployeeId,
                EmployeeName = employee.EmployeeName,
                Designation = employee.Designation,
                Email = employee.Email
            });
        }
        public async Task UpdateEmployee(Employee employee)
        {
            var filter = Builders<Employee>.Filter.Eq(e => e.Id, employee.Id);
            var update = Builders<Employee>.Update
                .Set(x => x.EmployeeName, employee.EmployeeName)
                .Set(x => x.EmployeeId, employee.EmployeeId)
                .Set(x => x.Designation, employee.Designation)
                .Set(x => x.Email, employee.Email);
                var result1 = await _collection.UpdateOneAsync(filter, update);
        }
        public async Task DeleteEmployee(Object id)
        {
            var filter = Builders<Employee>.Filter.Eq(e => e.Id, id);
            await _collection.DeleteOneAsync(filter);
        }
        }

 

Step 5 – I have written api action methods corresponding to the CRUD operations written in data access layer.

[RoutePrefix("api/Employees")]
    public class EmployeesController : ApiController
    {
        private EmployeeRepository _employeeRepository;
        public EmployeesController()
        {
            _employeeRepository = new EmployeeRepository();
        }
        [HttpGet]
        public async Task<IHttpActionResult> Get()
        {
            var employees = await _employeeRepository.GetAllEmployees();
            return Ok(employees);
        }
        [HttpGet]
        [Route("{id}")]
        public async Task<IHttpActionResult> Get(string id)
        {
            var employee = await _employeeRepository.GetEmployee(new ObjectId(id));
            return Ok(employee);
        }
        [HttpPost]
        public async Task<IHttpActionResult> Create(Employee employee)
        {
            await _employeeRepository.CreateEmployee(employee);
            return Ok();
        }
        [HttpPut]
        public async Task<IHttpActionResult> Update(Employee employee)
        {
            await _employeeRepository.UpdateEmployee(employee);
            return Ok();
        }
        [HttpDelete]
        [Route("{id}")]
        public async Task<IHttpActionResult> Delete(string id)
        {
            await _employeeRepository.DeleteEmployee(new ObjectId(id));
            return Ok();
        }
    }

You can test this out by using any api tools like Postman, RestClient etc.

Happy Coding 🙂

Get in Touch with Us

Guaranteed Response within One Business Day!

Latest Posts

April 18, 2024

The Complete Guide to Outsourcing Software Development

April 03, 2024

The Importance of Cybersecurity in Software Development

March 24, 2024

How to Manage Communication & Collaboration With Your Offshore Software Development Team

March 10, 2024

What Is the Importance of Software Maintenance

February 29, 2024

How Agile And DevOps Speed Up Product Development

Subscribe to our Newsletter!