MongoDB C#驅動


MongoDB C#驅動

http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial

筆記

首先下載驅動。驅動有兩個文件

  1. MongoDB.Bson.dll
  2. MongoDB.Driver.dll

可以直接下載這兩個驅動,或者按照下載源碼進行編譯生成。下載的源碼可以看些test例子。

在新建的c#工程中添加這兩個dll文件,並且使用如下命名空間

至少要引用如下命名空間

using MongoDB.Bson; 

using MongoDB.Driver; 
另外使用比較多的命名空間是
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;

 

另外有些可能會用得到的命名空間

using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver.Wrappers;
BSON類庫
BSON是類似JSON的一種二進制形式的存儲格式,簡稱Binary JSON,它和JSON一樣,支持內嵌的文檔對象和數組對象,但是BSON有JSON沒有的一些數據類型,如Date和BinData類型。它也是MongoDB文檔數據庫內部的數據存儲方式。
BsonType
 
public enum BsonType {
    Double = 0x01,
    String = 0x02,
    Document = 0x03,
    Array = 0x04,
    Binary = 0x05,
    Undefined = 0x06,
    ObjectId = 0x07,
    Boolean = 0x08,
    DateTime = 0x09,
    Null = 0x0a,
    RegularExpression = 0x0b,
    JavaScript = 0x0d,
    Symbol = 0x0e,
    JavaScriptWithScope = 0x0f,
    Int32 = 0x10,
    Timestamp = 0x11,
    Int64 = 0x12,
    MinKey = 0xff,
    MaxKey = 0x7f
}

BsonValue和子類

BsonValue是一種代表BsonType的虛擬類。它是BsonType枚舉類的凝聚子類。

·可以使用public構造函數生成BsonValue子類

·使用靜態create函數生成

·Use a static property of a subclass of BsonValue(靜態的子類屬性?)

·隱式轉換成BsonValue

BsonType的類型

可以用下面的例子代碼確認BsonValue的屬性

BsonValue value;
if (value.BsonType == BsonType.Int32) {
    // we know value is an instance of BsonInt32
}
if (value is BsonInt32) {
    // another way to tell that value is a BsonInt32
}
if (value.IsInt32) {
    // the easiest way to tell that value is a BsonInt32
}

As[Type] Properties

BsonValue有一系列轉換方式將它的類型cast(拋)(而不是conversion)成與.NET相匹配的數據類型。如果他不是一個.NET相對應的數據屬性,它將會拋出一個InvalidCastException 異常。下面是一些將數據轉變的方式。

BsonDocument document;
string name = document["name"].AsString;//As方式,類似轉變
int age = document["age"].AsInt32;
BsonDocument address = document["address"].AsBsonDocument;
string zip = address["zip"].AsString;

Is[Type] Properties

使用下面例子測試BsonValues是什么類型

BsonDocument document;
int age = -1;
if (document.Contains["age"] && document["age"].IsInt32) {//Is 是否為Int32類型
    age = document["age"].AsInt32;
}
To[Type] 轉變方法
與As不同,To是用於可以轉變類型之間的轉類型。比如int和double之間。
比如ToBoolen方法永遠不會失敗。它是按照javascript里面定義的。false, 0, 0.0, NaN, BsonNull, BsonUndefined 以及"" 是false,其他所有都是true。
if (employee["ismanager"].ToBoolean()) {
    // we know the employee is a manager
    // works with many ways of recording boolean values
}
ToDouble、ToInt32、以及ToInt64在數字之間的轉變都不會失敗。即使數字長度不匹配被縮短了都不會照成函數錯誤。string類型可以轉成數字類型。但是如果string類型不能轉成相應的數字的時候,會拋出異常。
隱式的轉化
下面的數據類型可以直接轉化
  • bool
  • byte[]
  • DateTime
  • double
  • Enum
  • Guid
  • int
  • long
  • ObjectId
  • Regex
  • string

比如下面

BsonValue b = true; // b is an instance of BsonBoolean
BsonValue d = 3.14159; // d is an instance of BsonDouble
BsonValue i = 1; // i is an instance of BsonInt32
BsonValue s = "Hello"; // s is an instance of BsonString

BsonMaxKey, BsonMinKey, BsonNull and BsonUndefined

這些數據類型是單個的類,要用到這些數據,需要使用各自的類來生成

document["status"] = BsonNull.Value;
document["priority"] = BsonMaxKey.Value;
注意,這個c#的null和BsonNull是兩個完全不同的東西。BsonNull是一個C#類,它的Value屬性是null。所以他們在函數構造不同。
 
ObjectId and BsonObjectId
一些常用的創建ObjectId 值的方式
var id1 = new ObjectId(); // same as ObjectId.Empty
var id2 = ObjectId.Empty; // all zeroes
var id3 = ObjectId.GenerateNewId(); // generates new unique Id
var id4 = ObjectId.Parse("4dad901291c2949e7a5b6aa8"); // parses a 24 hex digit string

在C#里面,剛創建的值默認都是零的。但是在javascript里面會創建一個唯一的值。

BsonElement

(Bson元素)
Bson元素是一個name/value的鍵值對。
document.Add(new BsonElement("age", 21)); // OK, but next line is shorter
document.Add("age", 21); // creates BsonElement automatically

BsonDocument

 
BsonDocument是name/value鍵值對的集合。
BsonDocument構造函數
  • BsonDocument()
  • BsonDocument(string name, BsonValue value)

上面是用的比較多

  • BsonDocument(BsonElement element)
  • BsonDocument(Dictionary<string, object> dictionary)
  • BsonDocument(Dictionary<string, object> dictionary, IEnumerable<string> keys)
  • BsonDocument(IDictionary dictionary)
  • BsonDocument(IDictionary dictionary, IEnumerable<string> keys)
  • BsonDocument(IDictionary<string, object> dictionary)
  • BsonDocument(IDictionary<string, object> dictionary, IEnumerable<string> keys)
  • BsonDocument(IEnumerabe<BsonElement> elements)
  • BsonDocument(params BsonElement[] elements)
  • BsonDocument(bool allowDuplicateNames)

創建一個新的document並且調用Add和Set函數

BsonDocument book = new BsonDocument();
book.Add("author", "Ernest Hemingway");
book.Add("title", "For Whom the Bell Tolls");
另外一種方式
BsonDocument book = new BsonDocument()
    .Add("author", "Ernest Hemingway")
    .Add("title", "For Whom the Bell Tolls");
使用c#的collection初始化語法(推薦)
BsonDocument book = new BsonDocument {
    { "author", "Ernest Hemingway" },
    { "title", "For Whom the Bell Tolls" }
};
編譯器會將它翻譯成調用Add函數的方式
    BsonDocument book = new BsonDocument();
    book.Add("author", "Ernest Hemingway");
    book.Add("title", "For Whom the Bell Tolls");
不要缺少里面的大括號,不然就會像下面一樣
BsonDocument bad = new BsonDocument {
    "author", "Ernest Hemingway"
};
編譯成:
BsonDocument bad = new BsonDocument();
bad.Add("author");
bad.Add("Ernest Hemingway");
創建嵌套的BSON documents
BsonDocument nested = new BsonDocument {
    { "name", "John Doe" },
    { "address", new BsonDocument {
        { "street", "123 Main St." },
        { "city", "Centerville" },
        { "state", "PA" },
        { "zip", 12345}
    }}
};
”address”是一個嵌套的document
 

ADD函數

  • Add(BsonElement element)
  • Add(Dictionary<string, object> dictionary)
  • Add(Dictionary<string, object> dictionary, IEnumerable<string> keys)
  • Add(IDictionary dictionary)
  • Add(IDictionary dictionary, IEnumerable<string> keys)
  • Add(IDictionary<string, object> dictionary)
  • Add(IDictionary<string, object> dictionary, IEnumerable<string> keys)
  • Add(IEnumerable<BsonElement> elements)
  • Add(string name, BsonValue value)
  • Add(string name, BsonValue value, bool condition)

如果里面的屬性值是null的話,add函數將不把數據加入到document中

BsonDocument document = new BsonDocument {
    { "name", name },
    { "city", city }, // not added if city is null
    { "dob", dob, dobAvailable } // not added if dobAvailable is false
};
可以翻譯成如下:
BsonDocument document = new BsonDocument();
document.Add("name", name);
if (city != null) {
    document.Add("city", city);
}
if (dobAvailable) {
    document.Add("dob", dob);
}
如果想add一個BsonNull值,可以使用C#中的null聯合
BsonDocument = new BsonDocument {
    { "city", city ?? BsonConstants.Null }
};
獲取BsonDocument的元素elements
  • BsonValue this[int index]
  • BsonValue this[string name]
  • BsonValue this[string name, BsonValue defaultValue]

返回的是BsonValue值,例子如下

BsonDocument book;
string author = book["author"].AsString;
DateTime publicationDate = book["publicationDate"].AsDateTime;
int pages = book["pages", -1].AsInt32; // default value is -1

BsonArray

這個類是用來表示BSON 數組。

構造函數

  • BsonArray()
  • BsonArray(IEnumerable<bool> values)
  • BsonArray(IEnumerable<BsonValue> values)
  • BsonArray(IEnumerable<DateTime> values)
  • BsonArray(IEnumerable<double> values)
  • BsonArray(IEnumerable<int> values)
  • BsonArray(IEnumerable<long> values)
  • BsonArray(IEnumerable<ObjectId> values)
  • BsonArray(IEnumerable<string> values)
  • BsonArray(IEnumerable values)

Add 和 AddRange 函數

  • BsonArray Add(BsonValue value)
  • BsonArray AddRange(IEnumerable<bool> values)
  • BsonArray AddRange(IEnumerable<BsonValue> values)
  • BsonArray AddRange(IEnumerable<DateTime> values)
  • BsonArray AddRange(IEnumerable<double> values)
  • BsonArray AddRange(IEnumerable<int> values)
  • BsonArray AddRange(IEnumerable<long> values)
  • BsonArray AddRange(IEnumerable<ObjectId> values)
  • BsonArray AddRange(IEnumerable<string> values)
  • BsonArray AddRange(IEnumerable values)
// traditional approach
BsonArray a1 = new BsonArray();
a1.Add(1);
a2.Add(2);

// fluent interface
BsonArray a2 = new BsonArray().Add(1).Add(2);

// values argument
int[] values = new int[] { 1, 2 };
BsonArray a3 = new BsonArray(values);

// collection initializer syntax
BsonArray a4 = new BsonArray { 1, 2 };

 

訪問

BsonArray array = new BsonArray { "Tom", 39 };
string name = array[0].AsString;
int age = array[1].AsInt32;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM