【转载】 mongodb C# 基本类库

本教程适用 C# Driver version v1.4.x,主要介绍2个类库:BSON & c#驱动,BSON 类库也是可以独立适用的,c#驱动类库是需要BSON类库支持的。

还有另外一个版本的教程   C#版 驱动 简单教程

引用命名空间

    MongoDB.Bson.dll
    MongoDB.Driver.dll

上面是运行的基本引用
还有以下的一些引用,在相应的时候用

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特定类型的定义

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 是一个抽象类,代表了一个输入Bson的值

BsonValue 有如下子类

    BsonArray
    BsonBinaryData
    BsonBoolean
    BsonDateTime
    BsonDocument
    BsonDouble
    BsonInt32
    BsonInt64
    BsonJavaScript
    BsonJavaScriptWithScope (a subclass of BsonJavaScript)
    BsonMaxKey
    BsonMinKey
    BsonNull
    BsonObjectId
    BsonRegularExpression
    BsonString
    BsonSymbol
    BsonTimestamp
    BsonUndefined


可以用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] 属性

   AsBoolean (=> bool)
    AsBsonArray
    AsBsonBinaryData
    AsBsonDateTime
    AsBsonDocument
    AsBsonJavaScript // also works if BsonType == JavaScriptWithScope
    AsBsonJavaScriptWithScope
    AsBsonMaxKey
    AsBsonMinKey
    AsBsonNull
    AsBsonRegularExpression
    AsBsonSymbol
    AsBsonTimestamp
    AsBsonUndefined
    AsBsonValue
    AsByteArray (=> byte[])
    AsDateTime (=> DateTime)
    AsDouble (=> double)
    AsGuid (=> Guid)
    AsInt32 (=> int)
    AsInt64 (=> long)
    AsNullableBoolean (=> bool?)
    AsNullableDateTime (=> DateTime?)
    AsNullableDouble (=> double?)
    AsNullableGuid (=> Guid?)
    AsNullableInt32 (=> int?)
    AsNullableInt64 (=> long?)
    AsNullableObjectId (=> ObjectId?)
    AsObjectId (=> ObjectId)
    AsRegex (=> Regex)
    AsString (=> string)


例子:

BsonDocument document;
string name = document["name"].AsString;
int age = document["age"].AsInt32;
BsonDocument address = document["address"].AsBsonDocument;
string zip = address["zip"].AsString;



Is[Type]属性

    IsBoolean
    IsBsonArray
    IsBsonBinaryData
    IsBsonDateTime
    IsBsonDocument
    IsBsonJavaScript
    IsBsonJavaScriptWithScope
    IsBsonMaxKey
    IsBsonMinKey
    IsBsonNull
    IsBsonRegularExpression
    IsBsonSymbol
    IsBsonTimestamp
    IsBsonUndefined
    IsDateTime
    IsDouble
    IsGuid
    IsInt32
    IsInt64
    IsNumeric (true if type is Double, Int32 or Int64)
    IsObjectId
    IsString

例子

BsonDocument document;
int age = -1;
if (document.Contains["age"] && document["age"].IsInt32) {
    age = document["age"].AsInt32;
}


To[Type] 转换方法

    ToBoolean
    ToDouble
    ToInt32
    ToInt64

例子:

if (employee["ismanager"].ToBoolean()) {
    // we know the employee is a manager
    // works with many ways of recording boolean values

}

隐式转换

    bool
    byte[]
    DateTime
    double
    Enum
    Guid
    int
    long
    ObjectId
    Regex
    string


BsonMaxKey, BsonMinKey, BsonNull and BsonUndefined

document["status"] = BsonNull.Value;
document["priority"] = BsonMaxKey.Value;



BsonElement

document.Add(new BsonElement("age", 21)); // OK, but next line is shorter
document.Add("age", 21); // creates BsonElement automatically



BsonDocument 


有三种方法创建
1.调用构造方法方式添加方法
2.通过平滑接口设置
3.c#的集合初始化


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)

前两个方法是常用的


创建一个 BsonDocument 

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#的集合初始化

BsonDocument book = new BsonDocument {
    { "author", "Ernest Hemingway" },
    { "title", "For Whom the Bell Tolls" }
};


创建嵌套 BSON documents

BsonDocument nested = new BsonDocument {
    { "name", "John Doe" },
    { "address", new BsonDocument {
        { "street", "123 Main St." },
        { "city", "Centerville" },
        { "state", "PA" },
        { "zip", 12345}
    }}
};


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)

有些时候要根据条件添加 

例如:
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);
}



访问 BsonDocument elements

    BsonValue this[int index]
    BsonValue this[string name]
    BsonValue this[string name, BsonValue defaultValue]
返回的值是 BsonValue  而不是BsonElement,如果想获得 BsonElements  ,可以用GetElement方法

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



BsonArray
BsonArray和BsonDocument 没有任何隶属关系。他们有不同的用处

BsonArray构造方法

    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 };


Indexer

访问BsonArray 也可以使用索引


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

原文地址:https://www.cnblogs.com/jecob/p/3691617.html