1. 程式人生 > >Mongodb學習一,開始使用C# Driver操作Mongodb

Mongodb學習一,開始使用C# Driver操作Mongodb

最近準備瞭解一下Mongodb,順便在這裡做一個總結。本章講解一下簡單的安裝和操作。

首先,安裝Mongodb:

D:\MongoDB

1、從官方下載好安裝包;

2、新建目錄“D:\MongoDB”,解壓安裝包,將bin目錄中的exe檔案拷貝到新建目錄之下;

3、在D:\MongoDB目錄下建立“Data”資料夾,開啟CMD視窗,切換到D:\MongoDB目錄,輸入“mongod --dbpath D:\MongoDB\Data ”。

結果如圖:


It looks like you are trying to access MongoDB over HTTP on the native driver port.

如此,MongoDB資料庫服務以及啟動。

最後,我們可以開始使用C#操作Mongodb了:

1、將以下DLL引入到工程:

  1. MongoDB.Bson.dll
  2. MongoDB.Driver.dll
2、直接拷貝官網的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace ConsoleApplication1
{
    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
	    //連結字串
            var connectionString = "mongodb://localhost";
	    //定義Mongo服務 
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
	    //獲取databaseName對應的資料庫,不存在則自動建立 
            var database = server.GetDatabase("test");
	    //獲取 "entities" 對應的集合,不存在則自動建立 
            var collection = database.GetCollection<Entity>("entities");

            var entity = new Entity { Name = "Tom" };
	    //將物件插入集合 
            collection.Insert(entity);
            var id = entity.Id;
<span style="white-space:pre">	</span>    // 定義查詢物件(id為entity.id,這裡為null)
            var query = Query<Entity>.EQ(e => e.Id, id);
	    // 在集合中查詢符合query條件的Entity物件
            entity = collection.FindOne(query);

            entity.Name = "Dick";
	    // 儲存物件,這裡將傳送到伺服器端
            collection.Save(entity);
	    // 更新物件,這裡只更新模型,不會發送到伺服器端
            var update = Update<Entity>.Set(e => e.Name, "Harry");
            collection.Update(query, update);
	    // 從集合中移除符合條件的物件
            collection.Remove(query);
        }
    }
}

單步除錯就可以看到結果了,當然也以在裡面加入一些輸出語句觀察結果。

執行完成後開啟資料資料夾,發現裡面多了 test.0和test.ns兩個檔案。

官方文件中有這樣一段話值得注意:

You Do NOT Need to Call Connect or Disconnect

The C# driver has a connection pool to use connections to the server efficiently. There is no need to callConnect or Disconnect; just let the driver take care of the connections (calling Connect

 is harmless, but calling Disconnect is bad because it closes all the connections in the connection pool).

意思不需要呼叫Connect(),或者Disconnect(),尤其後者,它將關閉連線池中的所有連線。