MongoDB操做集

 

官網html

https://www.mongodb.com/download-center#communitymongodb

基本資料:數據庫

http://www.runoob.com/mongodb/mongodb-intro.htmlwindows

下載地址:dom

https://www.mongodb.com/download-center/community異步

 

windows安裝:ui

安裝過程the domain,user name and/or password are incorrect.remember to use "." for the domain if the account is on the local machinespa

處理辦法:取消從新安裝code

 

使用:htm

與MongoDB通信的API類庫:

咱們將使用由MongoDB官方提供的API類庫來與MongoDB進行通信與交互,在Lezhima.Data項目中可經過NuGet管理器引用以下兩個類庫:

一、MongoDB.Bson

二、MongoDB.Driver

當插入數據時,若是不存在該數據庫則自動建立一個新的數據庫,若是不存在該集合則會自動建立一個集合

// 使用鏈接字符串鏈接
            var client = new MongoClient("mongodb://localhost:27017");
            // 制定多個地址和端口,讓程序自動選擇一個進行鏈接。
            //var client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");
            //獲取數據庫
            var database = client.GetDatabase("foo");
            //獲取數據集Collection
            var collection = database.GetCollection<BsonDocument>("bar");
            //插入數據
            var document = new BsonDocument {
                { "name", "MongoDB" },
                { "type", "Database" },
                { "count", 1 },
                { "info", new BsonDocument { { "x", 203 }, { "y", 102 } } }
            };
            //InsertOne(同步插入):
            collection.InsertOne(document);
            //InsertOneAsync(異步插入):
            await collection.InsertOneAsync(document);

//同步獲取數量

 var count = collection.Count(new BsonDocument());

//異步獲取集合數量

var count = await collection.CountAsync(new BsonDocument());

//讀取信息

var documents = collection.Find(new BsonDocument()).ToList();

若是返回的數據預期很大,建議採用如下異步的迭代的方法處理。

await collection.Find(new BsonDocument()).ForEachAsync(d => Console.WriteLine(d));

若是是在要用同步的方法,那麼能夠使用ToEnumerable適配器方法(數據量大的狀況):

var cursor = collection.Find(new BsonDocument()).ToCursor();
 string aa = "";
foreach (var document in cursor.ToEnumerable()) {
                aa += document + ",";
}

用過濾器篩選獲取單個數據

var filter = Builders<BsonDocument>.Filter.Eq("i", 71);

相關文章
相關標籤/搜索