Статьи

MongoDB с CSharp

Прежде чем вы начнете работать с MongoDB с помощью C Sharp, я рекомендую вам прочитать краткий обзор MongoDB для Windows за 5 минут и загрузить MongoDB для CSharp отсюда

Запустить сервер MongoDB

Если бы вы через 5 минут прошли через MongoDB в Windows, то вы знаете, как запустить сервер MongoDB. Однако просто для краткого обзора вам нужно запустить сервер MongoDB, как показано ниже,

Вы можете подключиться к серверу MongoDB, как показано ниже, выполнив mongod exe

образ


По умолчанию MongoDB хранит данные в папке данных диска C. Вам также необходимо явно создать эту папку.


Add required library in solution

You will get a solution when you download MongoDB for CSharp from here . Open the solution in Visual Studio and build it.

образ

Take MongoDB.dll and add this reference to your project.

Create Project and perform operations

For purpose of this blog post, I am going to create a console application. I have added MongoDB.dll as reference in console application project.


Create DataBase

If you want to create a database, you can create as below,

clip_image002

Above code will connect to MongoDB and create a database called Bloggers, if it does not exist.


Add Record in DataBase

You can add record as below,

clip_image002[6]

Where blogger is collection you get over database as below,

clip_image004


Delete Record from DataBase

image

You can delete a record by just providing one key value as well like below,

image

Fetch a Record

To fetch a particular document or record you need to create document and provide key value as below.

image

FindOne() function returns a document . You need to call Get function with key value as input to fetch the value.

For your reference full source code is as below,

01	using System;
02	using System.Collections.Generic;
03	using System.Linq;
04	using System.Text;
05	using MongoDB;
06	 
07	namespace ConsoleApplication34
08	{
09	class Program
10	{
11	static void Main(string[] args)
12	{
13	 
14	//Create Database
15	Mongo mongoDBdataBase = new Mongo();
16	mongoDBdataBase.Connect();
17	var dataBaseToWork = mongoDBdataBase.GetDatabase("Bloggers");
18	//Create Collection
19	var blogger = dataBaseToWork.GetCollection("blogger");
20	 
21	//Insert Records
22	var b = new Document();
23	b["Name"] = "Dhananjay";
24	b["Country"] = "India";
25	blogger.Insert(b);
26	b["Name"] = "G Block";
27	b["Country"] = "USA";
28	blogger.Insert(b);
29	 
30	//Fetch Record
31	var searchBlogger = new Document();
32	searchBlogger["Name"] = "Dhananjay";
33	var result = blogger.FindOne(searchBlogger);
34	Console.WriteLine(result.Get("Country").ToString());
35	 
36	Console.ReadKey(true);
37	 
38	}
39	}
40	}

In this way you can perform operations on MongoDB using CSharp. I hope this post is useful. Thanks for reading.

Source: http://debugmode.net/2012/01/22/mongodb-with-csharp/