ASP.Net MVC with Mongo DB
ASP.Net MVC with Mongo DB
If your plan is to use the MongoDB as a database in your
next project or you want to learn how to perform CRUD operation in MongoDB
using the ASP.Net MVC, so this article is going to help you in this. In this
example I am going to user the MVC 4.0 and MongoDB 3.6.1.
Prerequisite – Before we jump on the coding, we need to
install below software’s on development machine.
MongoDB
3.6.1 (Or the latest version)
MongoDB
Compass Community (GUI for MongoDB)
Let’s get started
Step 1 – Create a new MVC project
Step 2 – Add the MongoDB driver using the NuGet. Just search
for MongocsharpDriver and it find the driver for you.
Step 3 – Install MongoDB on your machine
Step 4 – Make sure that “Data” folder is created on the root
directory of the driver where MongoDB is installed. Otherwise, MongoDB will not
start.
Step 5 – Create the new database in MongoDB using the
Compass GUI or you can use the command prompt.
Step 6 – Once the database is ready, add the collection
(table) to the database.
Step 7 – Add following namespaces to the class
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
Step 8 - Select data from database.
var
connectionString = "mongodb://localhost";
MongoClient mongoClient = new MongoClient(connectionString);
MongoServer mongoServer = mongoClient.GetServer();
MongoDatabase mongoDatabase = mongoServer.GetDatabase(Your Database Name);
var collection = mongoDatabase.GetCollection<User>(Table Name);
//If
you have filter then add query.
var query = Query.And(
Query<User>.EQ(u => u.UserId,
model.UserName),
Query<User>.EQ(u => u.Password,
model.Password)
);
MongoCursor<User> result = collection.Find(query);
Note - User is a model. Create the model
based on your table structure.
Step 9 – Create record
var connectionString = "mongodb://localhost";
MongoClient mongoClient = new MongoClient(connectionString);
MongoServer mongoServer = mongoClient.GetServer();
MongoDatabase mongoDatabase = mongoServer.GetDatabase("FNOL");
var collection = mongoDatabase.GetCollection<RegisterUser>("PolicyHolderDetails");
BsonDocument claim = new BsonDocument
{
{"FirstName",model.FirstName},
{"LastName",model.LastName},
{"PolicyNumber",model.PolicyNumber},
{"Email",
model.Email},
{"Phone",model.Phone}
,
{"AdditionalPhone",model.AdditionalPhone},
{"StreetAddress",model.StreetAddress},
{"City",model.City},
{"State",model.State},
{"Zip",model.Zip}
};
collection.Insert(claim);
Comments