April 26, 2015 by Anuraj
.Net ASP.Net ASP.Net MVC Entity Framework Windows Azure
MongoDB (from humongous) is one of many cross-platform document-oriented databases. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open-source software.
Getting MongoDB Up and Running
- You can download and install MongoDB from https://www.mongodb.org/downloads based on your system configuration.
- Once installation is completed, you need to create a folder structure like this. C:\data\db (if you installed it on a different drive, instead of C: drive, specify the drive).
- Now you can run the mongod.exe from C:\Program Files\MongoDB\Server\3.0\bin. You can see a console window displaying several messages pertaining to initialization and listening.
- Run the mongo.exe, which is MongoDB administration shell. By default, the shell will connect to the MongoDB instance that you just started.
Working with MongoDB from ASP.NET application.
- Configure your project.json file to download MongoDB C# driver.
- You can connect to MongoDB using MongoClient class. GetDatabase() method of MongoClient class returns the MongoDB database instance. If the database doesn’t exists, MongoDB will create the database and returns an instance of IMongoDatabase.
- A Collection in MongoDB is loosely akin to a Table in SQL databases. Just as a Table may contain many related Rows, a Collection may contain many related Documents. IMongoDatabase.GetCollection
() returns a collection, with the name. If the collection doesn't exists, similar to Database, MongoDB will create the collection and returns an instance of IMongoCollection . So there is no problem even if you call the these methods many times.
- Here is the Model class. Instead of using integer Id property, Guid type is used. While creating the instance of the Employee class, I am assigning the default values.
- Create method. You can use InsertOneAsync method to insert a document to MongoDB.
- Update entity
- Delete an entity
- Read all entities from DB
You can specify filter conditions or Lamda expressions inside Find method, which will return specific entities. Here is a lamda expression to get one entity, using Find() method.
You can download the full source code from here
Here is the Mongo DB database and collection using RoboMongo.
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub