Click here to Skip to main content
14,218,548 members

MongoDB with .NET - Setup and CRUD operations

Rate this:
4.86 (13 votes)
Please Sign up or sign in to vote.
4.86 (13 votes)
3 Jan 2015CPOL
Article to elaborate MongoDB installation and performing CRUD operations with .NET

Introduction

MongoDB is one of the NoSQL DB used for better response for storing big volume of data and frequency in which data is accessed. For more information on Mongo DB you can refer the link . In this Article I have explained how to connect MongoDB with .Net application using console and perform CRUD operations.

Point covered in the article

1) MongoDB installation on Windows
2) Starting MongoDB
3) Creating objects and sample data
4) Connection with .Net Application
5) Performing CRUD operations
6) Get data using domain Class
 

MongoDB installation on Windows

To install the MongoDB on windows, download the latest release of MongoDB from here. Depending on version of your windows version download the setup. Windows version can be checked using the command "C:\>wmic os get osarchitecture" in the cmd window. In my case it is 64 bit and the MongoDB version available was “mongodb-win32-x86_64-2008plus-2.6.3”

Extract the zip file in folder where MongoDB is required to be setup. Example in this case “C:\Experiments\MongoDB\” is used. Rename the extracted folder to give friendly name.

Now MongoDB need a data directory to store data. So create new folder “Data\db” anywhere in drive. E.g. “C:\Experiments\Data\db”.

Starting MongoDB

Go to cmd prompt run the command, navigate to the bin directory present into the MongoDB installation folder and run the command mongod – dbpath {path of db folder}.Example. C:\Experiments\MongoDB\MongoDbServer\bin>mongod --dbpath "C:\Experiments\MongoDB\Data\db"

This will show waiting for connections message on the console output indicates that the mongod.exe process is running successfully.

Now to run the MongoDB you need to open another command prompt and use the following command. “C:\Experiments\MongoDB\MongoDbServer\bin>mongo”. It will show the version of MongoDb and connected database, By default it is test. Other window will show one connection is open.

Creating Collection and sample data

In MongoDB data is stored in collections. Commond db.createCollection(name, options) is used to create collection. Create two collections “States” and “Capital” using following command.

db.createCollection("States") & db.createCollection("Capital").

Message { "ok" : 1 } will be displayed to confirm collections are created successfully. Use command “show collections” to see the data.

Now to add sample data to “States and Capital” use following command

<code>db.States.insert([{Name:'Uttar Pradesh'},{Name: 'Panjab'},{Name: 'Haryana'},{Name: 'Himanchal'},{Name:'Maharashtra'}])</code>

<code>db.Capital.insert([{Name:'Lucknow','State': 'Uttar Pradesh'},{Name: 'Chandighar','State': 'Panjab'},{Name: 'Chandighar','State': 'Haryana'},{Name: 'Shimla','State': 'Himanchal'},{Name:'Mumbai','State': 'Maharashtra'}])</code>

 

Use db.States.find() command to see stored data. To know more about MongoDB commands please refer Link

Connection with .Net Application

Create a new .Net application e.g. console application. To connect to MongoDB we need add MongoDB drivers. The simplest way to get started is by using the nuget package.  Install required drivers “mongocsharpdriver” from Nuget package manager.

 

By default MongoDB run on 27017 port.  We can define new connection setting “Server=localhost:27017”.  To connect DB follow the below steps.

  1. Create new MongoClient object “client”, class MongoClient acknowledges all writes to MongoDB, in contrast to the existing connection class Db that has acknowledgements turned off.
  2. Create MongoServer : client.GetServer() which returns MongoServer type object, which is later used to query the desired database object.
  3. Create MongoDatabase “mongoDatabase” which returns MongoDatabase type object for the database used in this example test.

Below is the complete method to perform this operation. Run to see DB name in command prompt.

static void Main(string[] args) {
      string connectionString = "Server=localhost:27017";
      Console.WriteLine("Connecting MongoDB");
      MongoClient client = new MongoClient(connectionString);
      MongoServer server = client.GetServer();
      MongoDatabase mongoDatabase = server.GetDatabase("test");
      Console.WriteLine("Successfully connected to MongoDB: " + mongoDatabase.Name);
      Console.WriteLine("-----------------------------");   
}

 

 

 

 

Performing CRUD operations

Create data

To add new data in collection first retrieve collections and MongoCollection and use MongoCollection.Insert(BsonDocument) method to add new data in collection. The data type for MongoCollection is “BsonDocument”. Create new object of type BsonDocument and inset into the loaded collection. Below is the complete method to perform this operation.

private static MongoCollection<BsonDocument> CreateState(string stateName, MongoDatabase mongoDatabase) {
      MongoCollection<BsonDocument> states = mongoDatabase.GetCollection<BsonDocument>("States");
      BsonDocument state = new BsonDocument { { "Name", stateName } };
      states.Insert(state);
      return states;
}

Read data

Collections data is retried in a form of MongoCollection<BsonDocument> use mongoDatabase.GetCollection<BsonDocument>({CollectionName}) where CollectionName is the name of collections for which data is to be retrieved . Below is the complete method to perform this operation.

private static MongoCollection<BsonDocument> ReadState(MongoDatabase mongoDatabase) {
      MongoCollection<BsonDocument> states = mongoDatabase.GetCollection<BsonDocument>("States");
      return states;
    }

Update data

<o:p>For updating the data we can use FindAndModifyArgs. For  FindAndModifyArgs first query object to perform search on collection. Use Query.EQ("State", oldName) and update object to specify which object need to be updated Update.Set("State", newName). In this case as we don’t need to sort we can leave it as null. Below is the complete method to perform this operation.

private static MongoCollection<BsonDocument> UpdateCapital(MongoDatabase mongoDatabase, string oldName,string newName) {

      MongoCollection<BsonDocument> capitals = mongoDatabase.GetCollection<BsonDocument>("Capital"); 
	FindAndModifyArgs args = new FindAndModifyArgs() {
        Query = Query.EQ("State", oldName),
        Update = Update.Set("State", newName),
        Upsert = false,
        SortBy = null,
        VersionReturned = FindAndModifyDocumentVersion.Original,
      };
      FindAndModifyResult res = capitals.FindAndModify(args);     
      return capitals;

    }

Delete data

For delete data from the collection just create a query to search data from collection.  and use MongoCollection.Remove(query) method to remove data.

private static MongoCollection<BsonDocument> DeleteState(MongoDatabase mongoDatabase, string stateName) {
  MongoCollection<BsonDocument> capitals = mongoDatabase.GetCollection<BsonDocument>("Capital");
  var query = Query.EQ("State", stateName);
  capitals.Remove(query);
  return capitals;
}

 

Get data using domain Class

In real life scenarios we generally use domain classes to define objects rather than using BsonDocument. So let’s do that here as well. Create new public class state.

namespace Mongo {
public class State {
public string Name { get; set; }
public ObjectId Id { get; set; }
}
}


Define the attributes required for state and Id. Id will be of type ObjectId. This is MongoDB.Bson object used to define primary key for mongoDB collection. Crete new method ReadStateAsDomain.of type state. Below is a method.

 

private static MongoCollection<State> ReadStateAsDomain(MongoDatabase mongoDatabase) {
MongoCollection<State> states = mongoDatabase.GetCollection<State>("States");
return states;
}

Similarly Capital object can also be defined as domain class.

 

Thats all about installation and CRUD operations on MongoDB using .Net application. Its quite simple For any more detail about mongoDB operations please use follwing links

MongoDB doc

MongoDB database methods

C# MongoDB help

For compelete application download the attached source code.

License

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

Share

About the Author

Sudhir Dutt Rawat
Product Manager
India India
No Biography provided

Comments and Discussions

 
QuestionObjects and MongoDB Collections Pin
Member 111295666-Jan-15 21:18
memberMember 111295666-Jan-15 21:18 
AnswerRe: Objects and MongoDB Collections Pin
Sudhir Dutt Rawat6-Jan-15 21:40
memberSudhir Dutt Rawat6-Jan-15 21:40 

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.

Article
Posted 3 Jan 2015

Tagged as

Stats

36.9K views
1.4K downloads
33 bookmarked