MONDB方法运用

 1 namespace Mongodb
 2 {
 3     internal class Program
 4     {
 5 
 6 
 7         //[JsonConverter(typeof(ObjectIdConverter))] 有什么意议
 8         private static void Main(string[] args)
 9         {
10             Users odds = new Users() {Name = "小明", Sex = ""};
11 
12             string tableName = "EventSetting"; //表名称 
13             string dbName = "tx"; //数据库名称
14             string strconn = "mongodb://127.0.0.1:27017/?minPoolSize=5;maxPoolSize=100";
15             //连接字符串
16             //maxPoolSize最大连接池数量 
17             //minPoolSize最少连接池数量 
18             UpdataOrAdd(tableName, strconn, dbName, odds);
19 
20         }
21 
22         /// <summary>
23         /// 更新或增加
24         /// </summary>
25         /// <param name="tableName"></param>
26         /// <param name="strconn"></param>
27         /// <param name="dbName"></param>
28         /// <param name="odds"></param>
29         public static void UpdataOrAdd(string tableName, string strconn, string dbName, Users odds)
30         {
31             if (!string.IsNullOrEmpty(tableName)) //判断表名称是否为空
32             {
33 
34                 MongoServer server = MongoServer.Create(strconn); //创建连接通道
35                 MongoDatabase db = server.GetDatabase(dbName); //找到数据库(如果不存在则创建新数据库)
36                 MongoCollection col = db.GetCollection(tableName); //在db数据库存中找到表(如果不存在则在DB中创建新表)
37                 if (col != null) //判断是否为空,不为空则说明上述DB与表都存在
38                 {
39                     if (string.IsNullOrWhiteSpace(odds.SettingId)) //判断SettingId是否为空,如果为空说明表中并不存在
40                     {
41                         odds._id = ObjectId.GenerateNewId(); //生成新ID 注意:MODB会默认有_id作为标识,如果没有指定,系统也会自动生成此属性
42                         odds.SettingId = odds._id.ToString();
43                         WriteConcernResult result = col.Insert<Users>(odds); //插入对象
44                     }
45                     else
46                     {
47                         //判断此对象已存在,根椐_id唯一标识找到对象并一更新数据
48 
49                         IMongoQuery query = Query.EQ("_id", ObjectId.Parse(odds.SettingId));
50                         var update = MongoDB.Driver.Builders.Update.Set("Name", odds.Name);
51                         update.SetWrapped("Name", odds.Name);
52                         update.SetWrapped("Sex", odds.Sex);
53                         update.SetWrapped("SettingId", odds.SettingId);
54                         col.Update(query, update);
55 
56                     }
57                 }
58             }
59 
60         }
61     }   
62 }
63 public class Users
64 {
65 
66     public ObjectId _id;//BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId 
67 
68     public String ee { get; set; }
69     public string Name { get; set; }
70     public string SettingId { get; set; }
71     public string Sex { set; get; }
72 
73 }
MODB进门理解
string collectionName = "ddfdfd"; //表名称 
string dbName = "User"; //数据库名称
string strconn = "mongodb://127.0.0.1:27017/?minPoolSize=5;maxPoolSize=100";

if (!string.IsNullOrEmpty(collectionName))
{
//创建数据库链接
MongoServer server = MongoServer.Create(strconn);
//获得数据库
//MongoClientSettings s = new MongoClientSettings();
//s.MinConnectionPoolSize = 10;
MongoDatabase db = server.GetDatabase(dbName);

MongoCollection col = db.GetCollection(collectionName);
return col;
}
创建modb连接
 1         /// <summary>
 2         /// 通过某个id获取对应方案的详细数据
 3         /// </summary>
 4         /// <param name="id">查询_id</param>
 5         /// <returns></returns>
 6         public RunnerDescription GetHorseRunnersById(string id)
 7         {
 8             if (!string.IsNullOrWhiteSpace(id))
 9             {
10                 IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id));//条件
11                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
12                 if (col != null)
13                 {
14                     var result = col.FindOneAs<RunnerDescription>(query);
15                     return result;
16                 }
17             }
18             return null;
19         }
通过某个id获取对应方案的详细数据 col.FindOneAs<RunnerDescription>(query);
 1 /// <summary>
 2         /// 获取odds setting集合
 3         /// </summary>
 4         /// <returns></returns>
 5         public IList<MarketCatalogue> GetMarketList()
 6         {
 7             IList<MarketCatalogue> list = new List<MarketCatalogue>();
 8             MongoCollection col = MongoDBUtility.GetCollection(MarketCollection);
 9             if (col == null) return null;
10             MongoCursor<MarketCatalogue> m = col.FindAllAs<MarketCatalogue>();
11             if (m != null && m.Count() > 0)
12             {
13                 foreach (var item in m)
14                 {
15                     list.Add(item);
16                 }
17             }
18             return list;
19         }
查询所有集合(没有条件) col.FindAllAs<EventSeting>();
 1  public IList<RunnerDescription> GetHorseRunnersByMarketId(string id)
 2         {
 3             if (!string.IsNullOrWhiteSpace(id))
 4             {
 5                 IMongoQuery query = Query.EQ("MarketId", id);
 6 
 7                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
 8                 if (col != null)
 9                 {
10                     var result = col.FindAs<RunnerDescription>(query);
11                     IList<RunnerDescription> list = new List<RunnerDescription>();
12                     if (result != null && result.Count() > 0)
13                     {
14                         foreach (var item in result)
15                         {
16                             list.Add(item);
17                         }
18                     }
19                     return list;
20                 }
21             }
22             return null;
23         }
查询所有集合(带条件)col.FindAs(query)
 1  /// <summary>
 2         /// 编辑或添加odds setting对象
 3         /// </summary>
 4         /// <param name="odds"></param>
 5         /// <returns></returns>
 6         public string UpdateHorseRunners(RunnerDescription market)
 7         {
 8             if (market != null)
 9             {
10                 var obj = GetHorseRunnersByMarketIdAndRunnerId(market.MarketId, market.SelectionId);
11                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
12                 if (col != null)
13                 {
14                     if (obj == null)
15                     {
16                         if (market._id.ToString().StartsWith("000000"))
17                         {
18                             market._id = ObjectId.GenerateNewId();
19                         }
20                         WriteConcernResult result = col.Insert<RunnerDescription>(market);
21                         return market._id.ToString();
22                     }
23                     else
24                     {
25                         IMongoQuery query = Query.EQ("_id", market._id);
26                         var update = Update.Set("MarketId", market.MarketId);
27                         update.Set("SelectionId", market.SelectionId);
28                         update.Set("RunnerName", market.RunnerName);
29                         update.Set("Handicap", market.Handicap);
30                         update.Set("SortPriority", market.SortPriority);
31                         update.SetWrapped("Metadata", market.Metadata);
32                         col.Update(query, update);
33                     }
34                 }
35             }
36             return null;
37         }
更新或添加对象col.Insert(market);|| col.Update(query, update);
 1  public void UpdateHorseRunners(IList<RunnerDescription> runners)
 2         {
 3             if (runners != null && runners.Count>0)
 4             {
 5                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
 6                 if (col == null) return;
 7                 IList<long> rids = runners.Select(item => item.SelectionId).ToList();
 8 
 9                 MongoCursor<RunnerDescription> m = col.FindAs<RunnerDescription>(Query.In("SelectionId", new BsonArray(rids)));
10                 List<RunnerDescription> list=new List<RunnerDescription>();
11                 if (m != null && m.Count() > 0)
12                 {
13                     list.AddRange(m);
14                 }
15                 IList<RunnerDescription> insert=new List<RunnerDescription>();
16                 IList<RunnerDescription> update=new List<RunnerDescription>();
17                 foreach (var runner in runners)
18                 {
19                     string id = IsExist(list, runner.MarketId, runner.SelectionId);
20                     if (!string.IsNullOrWhiteSpace(id))
21                     {
22                         runner._id = ObjectId.Parse(id);
23                         update.Add(runner);
24                     }
25                     else
26                     {
27                         runner._id = ObjectId.GenerateNewId();
28                         insert.Add(runner);
29                     }
30                 }
31                 if (insert.Count > 0)
32                 {
33                     col.InsertBatch<RunnerDescription>(insert);
34                 }
35                 if (update.Count > 0)
36                 {
37                     foreach (var runner in update)
38                     {
39                         IMongoQuery query = Query.EQ("_id", runner._id);
40                         var update1 = Update.Set("Handicap", runner.Handicap);
41                         update1.Set("SortPriority", runner.SortPriority);
42                         update1.SetWrapped("Metadata",runner.Metadata);
43                         col.Update(query, update1);
44                     }
45                 }
46             }
47         }
插入(二个或以上对象)数组或集合()col.InsertBatch(集合或数组);当你要插入一个以上的文件,使用InsertBatch方法:常见错误:对象为空时会报错
 1  /// <summary>
 2         /// 添加odds setting对象
 3         /// </summary>
 4         /// <param name="odds"></param>
 5         /// <returns></returns>
 6         public string InsertHorseRunners(RunnerDescription market)
 7         {
 8             if (market != null)
 9             {
10                 var obj = GetHorseRunnersByMarketIdAndRunnerId(market.MarketId, market.SelectionId);
11                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
12                 if (col != null)
13                 {
14                     if (obj == null)
15                     {
16                         if (market._id.ToString().StartsWith("000000"))
17                         {
18                             market._id = ObjectId.GenerateNewId();
19                         }
20                         WriteConcernResult result = col.Insert<RunnerDescription>(market);
21                         return market._id.ToString();
22                     }
23                     
24                 }
25             }
26             return null;
27         }
插入一个对象col.Insert(market);
 1 /// <summary>
 2         /// 删除赛马的赔率
 3         /// </summary>
 4         /// <param name="query"></param>
 5         /// <returns></returns>
 6         public static bool DeteleHorseOdds()
 7         {
 8             IMongoQuery query = Query.EQ("_id", "550d19adcab03a32504101d6");
 9             MongoCollection col = GetCollection(TicketHorseCollection);
10             if (col != null)
11             {
12                 WriteConcernResult result = col.Remove(query);
13                 return true;
14             }
15             return false;
16         }
根椐条件删除某个对象: col.Remove(query); col.Remove(条件);
 1 using System.Data.Common;
 2 using System.Management.Instrumentation;
 3 using MongoDB.Bson;
 4 using MongoDB.Driver;
 5 using MongoDB.Driver.Builders;
 6 using System;
 7 using System.Collections.Generic;
 8 using System.Linq;
 9 using System.Text;
10 using System.Threading.Tasks;
11 
12 namespace Mongodb
13 {
14     internal class Program
15     {
16 
17 
18         //[JsonConverter(typeof(ObjectIdConverter))] 有什么意议
19         private static void Main(string[] args)
20         {
21             //Users odds = new Users() {Name = "小明", Sex = "女"};
22 
23             string tableName = "EventSetting"; //表名称 
24             string dbName = "tx"; //数据库名称
25             string strconn = "mongodb://127.0.0.1:27017/?minPoolSize=5;maxPoolSize=100";
26             //连接字符串
27             //maxPoolSize最大连接池数量 
28             //minPoolSize最少连接池数量 
29             UpdataOrAdd(tableName, strconn, dbName, odds);
30 
31         }
32 
33         /// <summary>
34         /// 更新或增加
35         /// </summary>
36         /// <param name="tableName"></param>
37         /// <param name="strconn"></param>
38         /// <param name="dbName"></param>
39         /// <param name="odds"></param>
40         public static void UpdataOrAdd(string tableName, string strconn, string dbName, Users odds)
41         {
42             if (!string.IsNullOrEmpty(tableName)) //判断表名称是否为空
43             {
44 
45                 MongoServer server = MongoServer.Create(strconn); //创建连接通道
46                 MongoDatabase db = server.GetDatabase(dbName); //找到数据库(如果不存在则创建新数据库)
47                 MongoCollection col = db.GetCollection(tableName); //在db数据库存中找到表(如果不存在则在DB中创建新表)
48                 col.RemoveAll();
49             }
50 
51         }
52 
53     }
54 
55     
56 }
删除所有col.RemoveAll();

 

 MongoDB C#驱动中Query几个方法
 1   MongoDB C#驱动中Query几个方法http://blog.csdn.net/dannywj1371/article/details/7575595
 2 
 3            Query.All("name", "a", "b");//通过多个元素来匹配数组
 4 
 5             Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同时满足多个条件
 6 
 7             Query.EQ("name", "a");//等于
 8 
 9             Query.Exists("type", true);//判断键值是否存在
10 
11             Query.GT("value", 2);//大于>
12 
13             Query.GTE("value", 3);//大于等于>=
14 
15             Query.In("name", "a", "b");//包括指定的所有值,可以指定不同类型的条件和值
16 
17             Query.LT("value", 9);//小于<
18 
19             Query.LTE("value", 8);//小于等于<=
20 
21             Query.Mod("value", 3, 1);//将查询值除以第一个给定值,若余数等于第二个给定值则返回该结果
22 
23             Query.NE("name", "c");//不等于
24 
25             Query.Nor(Array);//不包括数组中的值
26 
27             Query.Not("name");//元素条件语句
28 
29             Query.NotIn("name", "a", 2);//返回与数组中所有条件都不匹配的文档
30 
31             Query.Or(Query.EQ("name", "a"), Query.EQ("title", "t"));//满足其中一个条件
32 
33             Query.Size("name", 2);//给定键的长度
34 
35             Query.Type("_id", BsonType.ObjectId );//给定键的类型
36 
37             Query.Where(BsonJavaScript);//执行JavaScript
38 
39             Query.Matches("Title",str);//模糊查询 相当于sql中like  -- str可包含正则表达式
MongoDB C#驱动中Query几个方法 http://blog.csdn.net/dannywj1371/article/details/7575595

MongoDB(C#)Insert()与InsertBatch原子批量插入详解

MongoDB(C#)系列四 原子批量插入 - Francis Wang
时间 2013-10-21 21:21:00  博客园-原创精华区
原文  http://www.cnblogs.com/francisYoung/p/3381397.html
插入一个document和插入多个document的用法差不多,下面重点演示插入多个document的用法,并演示一个原子的批量插入。 
1.插入一个document 
可以调用MongoCollection的Insert方法插入一个document。Insert方法有如下几个版本:

public virtual WriteConcernResult Insert<TNominalType>(TNominalType document);
public virtual WriteConcernResult Insert<TNominalType>(TNominalType document, MongoInsertOptions options);
public virtual WriteConcernResult Insert<TNominalType>(TNominalType document, WriteConcern writeConcern);
第一个方法比较简单,第二个方法和第三个方法的使用和批量插入原理一样。 
2.批量插入

public virtual IEnumerable<WriteConcernResult> InsertBatch(IEnumerable<TDefaultDocument> documents);

public virtual IEnumerable<WriteConcernResult> InsertBatch(IEnumerable<TDefaultDocument> documents, MongoInsertOptions options);

public virtual IEnumerable<WriteConcernResult> InsertBatch(IEnumerable<TDefaultDocument> documents, WriteConcern writeConcern);
可以调用InsertBatch方法向集合中插入一个数组,集合。下面演示如何插入一个数组。 
为了插入一个数组,首先定义他,如下:

var batch = new BsonDocument[] { 
new BsonDocument("x",1),
new BsonDocument("x",2),
new BsonDocument("x",3)
};
然后调用InsertBatch方法插入这个数组:

collection.InsertBatch(batch);
下面验证是否插入成功:

Console.WriteLine("count:{0}",collection.Count());//这里输出3

var result=collection.FindOne(Query.EQ("x",2));
Console.WriteLine("the value of x field in result:{0}",result["x"].AsInt32);//这里输出2
OK,插入成功。 
完整代码:

private static void InsertBatchDemo() {
            var connetionString = "mongodb://localhost/";
            var mongoUrl = new MongoUrl(connetionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            var client = new MongoClient(clientSettings);

            var mongoServer = client.GetServer();
            var database = mongoServer.GetDatabase("firstDb");
            var collection = database.GetCollection("student");
            //为了便于测试,如果这个集合以及存在,先删除。
            collection.Drop();

            var batch = new BsonDocument[] { 
                new BsonDocument("x",1),
                new BsonDocument("x",2),
                new BsonDocument("x",3)
            };

            collection.InsertBatch(batch);

            Console.WriteLine("count:{0}",collection.Count());

            var result=collection.FindOne(Query.EQ("x",2));
            Console.WriteLine("the value of x field in result:{0}",result["x"].AsInt32);
           
        }
3.如何处理插入过程中出现的错误。 
为了便于演示,首先定义一个包含有重复值的数组:

var batch = new BsonDocument[] { 
new BsonDocument("x",1),
new BsonDocument("x",2),
new BsonDocument("x",2),
new BsonDocument("x",3)
};
如果集合中在x字段上存在一个唯一索引,那么插入batch时,就会在插入第二个 BsonDocument("x",2)处失败,后面的元素就不会再插入。

现在,我想要在插入batch时,即使出现了重复值,我依旧想要插入BsonDocument("x",3)。这时就要用到InsertBatch的第二个重载方法了,如下:

public virtual IEnumerable<WriteConcernResult> InsertBatch(IEnumerable<TDefaultDocument> documents, MongoInsertOptions options);
InsertBatch方法接受一个MongoInsertOptions参数,现在构造他:

MongoInsertOptions options = new MongoInsertOptions {
  Flags=InsertFlags.ContinueOnError
};
通过为option的Flags属性指定一个InsertFlags.ContinueOnError参数,可以在插入batch时即使出现了错误,也要继续插入后面的元素。 
完整代码:

private static void InsertBatchContinueOnErrorDemo() {
            var connetionString = "mongodb://localhost/";
            var mongoUrl = new MongoUrl(connetionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            var client = new MongoClient(clientSettings);

            var mongoServer = client.GetServer();
            var database = mongoServer.GetDatabase("firstDb");
            var collection = database.GetCollection("student");

            //为了便于测试,如果这个集合以及存在,先删除。
            collection.Drop();

            //在x字段上添加一个唯一索引。
            collection.EnsureIndex(IndexKeys.Ascending("x"),IndexOptions.SetUnique(true));


            var batch = new BsonDocument[] { 
                new BsonDocument("x",1),
                new BsonDocument("x",2),
                new BsonDocument("x",2),
                new BsonDocument("x",3)  
            };

            MongoInsertOptions options = new MongoInsertOptions {
                Flags=InsertFlags.ContinueOnError//插入过程出现错误时,继续插入后面的元素。
            };
            
            //在插入batch时,由于值中重复所以会引发一个WriteConcernException异常。
            //没关系,这个异常仅仅是告诉我们batch中具有重复值而已。
            try {
                collection.InsertBatch(batch,options);
            } catch (WriteConcernException) {
                 Console.WriteLine("count:{0}", collection.Count());//这里将输出三,表明集合中三条记录

                 //这里查看一下BsonDocument("x",3)是否插入成功
                 var result = collection.FindOne(Query.EQ("x",3));
                 //输出3,表明BsonDocument("x",3)已经插入成功
                 Console.WriteLine("the value of x field in result:{0}",result["x"].AsInt32);
            }
           
        }
总结:可以使用Insert插入单个文档,使用InsertBatch插入批量文档。默认情况下,使用InsertBatch批量插入时,如果中间出现了错误,后面的元素将不会在插入,但是前面的元素是成功插入到数据库集合中的。 
如果想要在插入过程中出现了错误的话,以后的元素也要插入进去,此时要使用MongoInsertOptions来进行一下配置。 
MongoDB(C#)系列四 原子批量插入http://www.tuicool.com/articles/JVNjue

MongoDB的C#驱动程序教程(译)

   1 MongoDB的C#驱动程序教程(译)
   2 草案版本(日期为2010-09-30   3 该文件是一个草案版本。虽然我们认为这里提供的信息是非常准确的,它是可能的,它可能会改变未成年人的方式,因为我们吸收用户的反馈意见,并继续执行 C#驱动程序。
   4 
   5 1.概述
   6 本教程是10gen支持C#驱动程序MongoDB的介绍。假定您熟悉使用MongoDB,因此主要集中在如何使用C#访问MongoDB的。 它分为两个部分:C# 驱动程序 ,BSON图书馆。C#驱动程序是建立在顶部,其目的是单独使用的C#驱动程序的的BSON图书馆,。
   7 
   8 在第1部分中,我们将介绍C#驱动程序的主类:MongoServer,MongoDatabase,MongoCollection,MongoCursor,MongoGridFS,MongoGridFSFileInfo和SafeMode。
   9 
  10 在第2部分,我们将讨论的主要类的BSON Library的:BsonType,BsonValue(及其子类),BsonElement,BsonDocument和BsonArray。
  11 
  12 第1部分:C#驱动程序
  13 本教程的第1部分组织自顶向下的方式,所以你有时可能提前偷看,如果事情是没有意义。您甚至可能想要读第2,如果你是完全陌生的的BSON概念,如文档和元素与前第1部分。
  14 
  15 参考文献和命名空间
  16 为了从你的程序中使用C#的驱动程序,您必须添加以下两个DLL文件:
  17 
  18 MongoDB.BsonLibrary.dll
  19 MongoDB.CSharpDriver.dll
  20 您还应该添加以下语句到你的源文件:
  21 
  22 using MongoDB.BsonLibrary;
  23 
  24 using MongoDB.CSharpDriver;
  25 
  26  
  27 
  28 除了 极少数例外,你将要使用的类的名称前缀与任何“BSON”的,如果他们的BsonLibrary或“Mongo”的一部分,如果他们的C#驱动程序的一部分 。这样做是为了获得名称冲突的可能性降至最低,当您添加到你的程序的两个使用语句。预计将方法的参数(主要是枚举和标志)的一些类,具有较短的名称,不使用任何前缀。
  29 
  30 我们喜欢使用C#的var语句声明 的变量,因为它会导致更短,我们的感觉,更可读的代码。Visual Studio可以很容易地看到一个变量的类型 ,如果您需要通过将鼠标指针悬停在变量 或使用IntelliSense。然而,当阅读本文档,你没有这个能力,所以在这个文件中,而不是写:
  31 
  32               var server = MongoServer.Create(connectionString);
  33 
  34               var test = server[“test”];
  35 
  36               var books = test[“books”];
  37 
  38  
  39 
  40 按照我们的建议,我们会来写:
  41 
  42               MongoServer server = MongoServer.Create(connectionString);
  43 
  44               MongoDatabase test = server[“test”];
  45 
  46               MongoCollection<BsonDocument> books = test[“books”];
  47 
  48  
  49 
  50 所以,你可以看到什么类型正在使用。
  51 
  52 线程安全
  53 只有少数的C#驱动程序 类是线程安全的。其中:MongoServer的,MongoDatabase,MongoCollection MongoGridFS。通用类,你会使用很多是不是线程安全包括MongoCursor的所有类的BsonLibrary(除BsonSymbolTable)的。A类不是线程安全的,除非特别记载是线程安全的。
  54 
  55 所有的所有类的静态属性和方法是线程安全的。
  56 
  57 MongoServer类
  58 这个类服务 s的工作与MongoDB的根对象。这个类的一个实例的客户端是一个MongoDB服务器,你想沟通。虽然这个类有公共的构造函数,推荐的方式来获得这个类的一个实例是使用工厂方法。
  59 
  60 每个实例MongoServer保持与服务器的连接池。这些连接之间共享所有的呼叫到服务器。你可能要调用构造函数,而不是直接调用创建工厂方法MongoServer的几个原因之一是,如果你要保持一个单独的连接池的一些操作。
  61 
  62 这个类的实例是线程安全的。
  63 
  64 连接字符串
  65 最简单的方法是使用一个连接字符串连接到MongoDB的。标准 MongoDB的连接字符串的格式是一个以下列格式的URL:
  66 
  67               mongodb://[username:password@]hostname[:port][/database]
  68 
  69  
  70 
  71 如果您使用的是MongoDB服务器的身份验证的用户名和密码,只应。这些凭据将适用于一个单一的数据库,如果数据库名称是存在的,否则他们将所有的数据库的默认凭据。要进行身份验证对管理数据库追加“(管理)”的用户名的。
  72 
  73 端口号是可选的,默认为27017。
  74 
  75 如果数据库名是存在的,那么这个连接字符串,也可以与创建方法MongoDatabase的使用。创建方法MongoServer忽略的数据库名称(如果存在)(以外的凭据,以确定是否适用于一个单一的数据库或所有数据库的默认凭据)。
  76 
  77 要连接到一个副本设置指定的种子提供多个以逗号分隔的主机名列表。例如:
  78 
  79               mongodb://server1,server2:27017,server2:27018
  80 
  81  
  82 
  83 该连接字符串指定的种子名单,由三个服务器(其中两个是在同一台机器上,但在不同的端口号)。
  84 
  85 C#驱动程序 能够连接到副本集,即使种子名单是不完整的。它会发现在主服务器即使主只要不是种子列表中的种子列表上的至少一个次级服务器响应(响应将包含完整副本集和当前的主的名称)。
  86 
  87 工厂方法
  88 最好的方式得到的一个实例MongoServer是,使用CREATE工厂方法。使用相同的连接字符串时,此方法将返回相同的实例MongoServer,所以你不必担心一大堆的情况下,如果你调用Create不止一次。此外,如果你只使用一个数据库时,你可能会发现它更容易跳过调用此方法,并呼吁建立 工厂方法MongoDatabase。
  89 
  90 要连接到MongoDB的本地,你会写这样的代码:
  91 
  92               string connectionString = “mongodb://localhost”;
  93 
  94               MongoServer server = MongoServer.Create(connectionString);
  95 
  96  
  97 
  98 或许......
  99 
 100               MongoServer server = MongoServer.Create();
 101 
 102  
 103 
 104 因为连接到本地主机是默认的。
 105 
 106 中的Create方法MongoServer忽略了数据库名称,如果存在的话。但是,如果省略数据库名称,但存在凭据,然后MongoServer将承担这些凭据要使用的所有数据库,将它们存储在MongoServer的Credentials属性,并利用它们时GetDatabase被称为无凭据的默认凭据。这使得它真正易于使用相同的凭证与所有的数据库。
 107 
 108 Create方法使用的种子列表中的服务器的身份时,如果已经有一个现有的实例MongoServer返回(而不是实际的副本集的成员,直到建立连接后,不知道是受改变)。
 109 
 110 安全模式属性
 111 此属性表示此服务器的默认安全模式。返回此服务器实例的MongoDatabase任何情况下,它会被继承,但可以改变indepently服务器的数据库的默认安全模式。安全模式类有进一步的描述。
 112 
 113 GetDatabase方法
 114 ,从一个实例MongoServer你可以代表该服务器上的数据库使用GetDatabase方法的对象的实例。要得到一个数据库对象,你可以这样写:
 115 
 116               MongoDatabase test = server.GetDatabase(“”);
 117 
 118  
 119 
 120  121 
 122               MongoDatabase test = server[“test”];
 123 
 124  
 125 
 126 这两种形式是完全等效的。如果您使用的认证,就必须写略有不同的代码,如:
 127 
 128               MongoCredentials credentials =
 129 
 130 new MongoCredentials(“username”, “password”);
 131 
 132               MongoDatabase test = server.GetDatabase(“test”, credentials);
 133 
 134  
 135 
 136  137 
 138               MongoDatabase test = server[“test”, credentials];
 139 
 140  
 141 
 142 MongoServer维护一个表的MongoDatabase实例的数据库/凭据组合,并每次你问相同的数据库/凭据组合,你得到相同的实例MongoDatabase,所以你无需担心不必要的重复的实例存在。
 143 
 144 MongoDatabase类
 145 这个类表示一个MongoDB服务器上的数据库。除非你正在使用的身份验证,你通常有 您要为每个数据库这一类 只有 一个实例。如果您正在使用的身份验证,那么 , 你 最终会为每个数据库/凭据的组合,你要使用这个类的一个实例。
 146 
 147 这个类的实例是线程安全的。
 148 
 149 但是,如果你正在编写一个多线程程序,并做了一系列的相关操作(这是很常见的!),你可能希望使用的RequestStart,/ RequestDone,以确保一个线程的相关操作都发生在同一连接上的服务器。
 150 
 151 工厂方法
 152 通常情况下你的服务器实例上调用GetDatabase获得的MongoDatabase的实例,但 MongoDatabase也有创建工厂方法,这需要一个URL作为一个参数。但在这种情况下,数据库的名称是 必需的,将抛出一个异常,如果它缺少的URL。如果你选择到使用的创建工厂方法在MongoDatabase你做不有来电的创建工厂方法在MongoServer(虽然它会被称为为您和的导致服务器对象是提供给您,如果需要的新的数据库实例的服务器属性) 。
 153 
 154 使用创建工厂方法,你能写的MongoDatabase要创建一个实例:
 155 
 156               string connectionString = “mongodb://localhost/test”;
 157 
 158               MongoDatabase test = MongoDatabase.Create(connectionString);
 159 
 160               MongoServer server = test.Server; // 如果需要的话
 161 
 162  
 163 
 164 请注意,这是完全等价于下面的代码:
 165 
 166               string connectionString = “mongodb://localhost/test”;
 167 
 168               MongoServer server = MongoServer.Create(connectionString);
 169 
 170               MongoDatabase test = server.GetDatabase(“”);
 171 
 172  
 173 
 174 第一种形式是有利的,如果你不直接访问服务器对象,也因为来自URL的数据库名称(如果存在的凭据),并没有硬编码。
 175 
 176 服务器属性
 177 这个属性允许你导航回从MongoDatabase对象,的MongoServer对象,它属于。
 178 
 179 Credentials属性
 180 这个属性允许你检查这个的MongoDatabase实例关联的凭据。你不能改变的凭据。如果你想用不同的凭据,你必须回到服务器对象并得到一个新的数据库对象的新的 凭证。这通常是由许多部分的 代码 共享因为MongoDatabase的一个实例 ,并更改凭证,可能会产生意想不到的副作用。
 181 
 182 安全模式属性
 183 此属性表示该数据库的默认安全模式。返回该数据库实例的MongoCollection任何情况下,它会被继承,但可以改变一个集合的默认安全模式indepently数据库的。安全模式类有进一步的描述。
 184 
 185 GridFS property
 186 此属性使您可以访问这个数据库关联的的GridFS对象的。请参阅下面的MongoGridFS类的描述。MongoGridFS类的方法,如上传,下载,查找,让您的GridFS文件系统进行交互。
 187 
 188 GetCollection方法
 189 ,从一个实例MongoDatabase你可以得到代表在该数据库使用GetCollection方法的集合对象的实例。为了得到一个集合对象,你可以这样写:
 190 
 191               MongoCollection<BsonDocument> books =
 192 
 193                             database.GetCollection(“books”);
 194 
 195  
 196 
 197  198 
 199               MongoCollection<BsonDocument> books = database[“books”];
 200 
 201  
 202 
 203 这两种形式是完全等效的。
 204 
 205 MongoDatabase维护一个表,至今已经使用的集合,每一次你问的同一个集合中,你得到相同的实例,所以你就不需要担心不必要的重复的实例存在。
 206 
 207 GetCollection <TDefaultDocument>方法
 208 在MongoDB中集合的特点之一是,他们是无架构。然而,它也是不寻常的一个集合 主要 持有 一种类型 的文件。我们称此为默认文档类型。通常情况下,默认的文件类型是BsonDocument,但你可以指定一个不同的默认文件类型的集合通过使用GetCollection <TDefaultDocument> 方法。例如:
 209 
 210               MongoCollection<Employee> employees =
 211 
 212                             Database.GetCollection<Employee>(“employees”);
 213 
 214  
 215 
 216 有没有索引等效的,因为C#不允许的类型参数索引。
 217 
 218 即使一个集合有一个默认的文件类型,你可以随时查询任何其他类型的文件,使用查找<TQuery, TDocument>方法,而不是查找<TQuery>(查找的<TQuery>仅仅是一个方便的快捷键<TQuery的, TDefaultDocument>)。
 219 
 220 C#驱动程序的最初版本只支持与文件类型BsonDocument的(因为BSON序列化/反序列化的支持尚未实现,对于其他类型)。
 221 
 222 DropCollection方法
 223 此方法可以用于从数据库中删除一个集合。MongoCollection也有一个方法叫做removeall过下降的数据,但在叶集(及任何索引)。要使用此方法写:
 224 
 225               BsonDocument result = database.DropCollection(“books”);
 226 
 227  
 228 
 229 DropCollection实际上是一个数据库命令的包装。所有的方法来包装一个命令返回命令的结果,这在某些情况下,可能有您感兴趣的信息。
 230 
 231 RequestStart方法/ RequestDone方法
 232 它经常发生,一个线程执行一系列数据库操作 有关重新 。更重要的是,线程 有时确实是依赖于早期写的读入。如果读出的发生比写要完成的一个不同的连接有时结果将尚未提供。一个线程可以表明它已被使用RequestStart一个 第二,它是一系列相关的操作由Cal 灵RequestDone 做了一系列的相关操作 。例如:
 233 
 234               database.RequestStart();
 235 
 236               / /数据库的操作做了一系列的
 237 
 238               database.RequestDone();
 239 
 240  
 241 
 242 这个例子其实是有一个小问题:如果抛出一个异常,而这样做 对数据库的操作RequestDone永远不会被调用。要预防,你可以把到RequestDone在一个最后的块,或更容易的调用,利用,RequestStart返回一个帮手对象实现IDisposable的实例 , 并使用了C#使用陈述保证,RequestDone被称为自动。在这种情况下,你这样写:
 243 
 244               using (database.RequestStart()){
 245 
 246                             / /数据库的操作做了一系列的
 247 
 248               }
 249 
 250  
 251 
 252 请注意,在这种情况下,你不叫RequestDone自己,这种情况发生时,会自动离开using语句的范围。
 253 
 254 RequestStart的增量一计数器和RequestDone的的减少,所以你可以嵌套调用到RequestStart和RequestDone的要求实际上是不开 ,直到 再次达到零。这有助于当你执行方法,需要调用RequestStart / RequestDone的 , 但 称为的代码本身RequestStart的在转。 这方面的一个例子是上载的方法在MongoGridFS,这要求RequestStart / RequestDone的。由于RequestStart筑巢产卵的行为是完全没有上传代码,已经本身称为RequestStart的调用。
 255 
 256 MongoCollection <TDefaultDocument> 257 在MongoDB数据库中, 这个类的实例 参阅下文的集合。你会得到一个的MongoCollection实例通过调用 GetCollection或GetCollection <TDefaultDocument>的方法MongoDatabase。 的类型参数TDefaultDocument的 是这个集合中的默认文档类型(如果你不指定,否则这将是BsonDocument)。
 258 
 259 这个类的实例是线程安全的。
 260 
 261 数据库属性
 262 这个属性允许你导航回从MongoCollection对象,的MongoDatabase对象,它属于。
 263 
 264 安全模式属性
 265 此属性表示该集合中的默认安全模式。这将是对这个集合进行操作的默认安全模式,但已有许多方法提供了一种方法来覆盖安全模式只是一个操作。安全模式类有进一步的描述。
 266 
 267 插入<TDocument>方法
 268 之前,我们可以从集合中获取任何信息,我们需要把它放在那里。Insert方法的一种方式插入到一个集合中的文件(也可以查看保存的方法和UPSERT版本的Update方法)。例如:
 269 
 270               BsonDocument book = new BsonDocument {
 271 
 272                             { “author”, “Ernest Hemingway” },
 273 
 274                             { “title”, “For Whom the Bell Tolls” }
 275 
 276               };
 277 
 278               books.Insert(book);
 279 
 280  
 281 
 282 INSERT语句也可以写成:
 283 
 284               books.Insert<BsonDocument>(book);
 285 
 286  
 287 
 288 但是这是没有必要的,因为编译器可以推断 从参数 类型 TDocument的。需要注意的是TDocument 必须是一个类型,可以被序列化到一个BSON文档。C#驱动程序 的最初版本 只知道如何序列化的BsonDocument类的实例。
 289 
 290 当你要插入一个以上的文件,使用InsertBatch方法 。例如:
 291 
 292               BsonDocument[] batch = {
 293 
 294 new BsonDocument {
 295 
 296                             { “author”, “Kurt Vonnegut” },
 297 
 298                             { “title”, “Cat’s Cradle” }
 299 
 300               }
 301 
 302               new BsonDocument {
 303 
 304                             { “author”, “Kurt Vonnegut” },
 305 
 306                             { “title”, “Slaughterhouse-Five” }
 307 
 308               }
 309 
 310 };
 311 
 312               books.InsertBatch(batch);
 313 
 314  
 315 
 316 在一次插入多个文件的优点是,它最大限度地减少了网络传输。被插入的所有文件被发送到服务器在一个消息中(除非序列化的文件的总大小超过16MB,在这种情况下,它们将被在多个消息发送各保持为尽可能多的文件)。
 317 
 318 <TQuery>方法
 319 最常见的操作,您将执行对集合进行查询。这样做的find方法的几个变化。在本教程中,我们只显示简单的表格S, 但也有其他形式,让您使用JavaScript where子句而不是一个查询对象和/或指定要返回的字段。
 320 
 321 下面是一些示例代码来读取的文件,我们刚刚插入的藏书:
 322 
 323               BsonDocument query = new BsonDocument {
 324 
 325                             { “author”, “Kurt Vonnegut” }
 326 
 327               };
 328 
 329               MongoCursor<BsonDocument> cursor = books.Find(query);
 330 
 331               foreach (BsonDocument book in cursor) {
 332 
 333 ConsoleWriteLine。
 334 
 335                                           “{0} {1}”,
 336 
 337 book[“title”].AsString,
 338 
 339 book[“author”].AsString
 340 
 341 );
 342 
 343               }
 344 
 345  
 346 
 347 如果该文件被退回是不是默认的文件类型,然后使用一个版本的查找,可以让你指定的文件类型:
 348 
 349               MongoCursor<Employee> cursor =
 350 
 351 employees.Find<BsonDocument, Employee>(query);
 352 
 353  
 354 
 355 有很多形式的查询对象的支持,但他们不是具体 到C#驱动程序 ,我们没有足够的空间来形容他们。一个空的查询对象检索的所有文件, 相当于一个空的查询对象 的 C#驱动程序允许空。
 356 
 357 还有很多说关于MongoCursor,但有一整节以下使用游标在那里寻找更多详细信息。
 358 
 359 FindAll方法
 360 这种方法仅仅是一个快捷方式FindAll扩展<TDefaultDocument> 和检索的所有文件的集合。例如:
 361 
 362               MongoCursor<BsonDocument> cursor = books.FindAll();
 363 
 364               foreach (BsonDocument book in cursor) {
 365 
 366                             Console.WriteLine(
 367 
 368                                           “{0} {1}”,
 369 
 370 book[“title”].AsString,
 371 
 372 book[“author”].AsString
 373 
 374 );
 375 
 376               }
 377 
 378  
 379 
 380 要查询一个文件,是不是默认的文件类型使用FindAll扩展<TDocument> 381 
 382 FindOne <TQuery>方法
 383 如果你知道有只有一个匹配的文件或如果你只是想第一个匹配的文件,你可以使用FindOne方法。例如:
 384 
 385               BsonDocument query = new BsonDocument {
 386 
 387                             { “author”, “Kurt Vonnegut” }
 388 
 389               };
 390 
 391               BsonDocument book = books.FindOne(query);
 392 
 393  
 394 
 395 FindOne返回它找到第一个匹配的文件或C#NULL,如果 是没有的。如果进一步 e是一个以上的匹配文档,它没有指定哪一个将被退回。
 396 
 397 FindOne <TQuery>实际上是一个快捷方式:
 398 
 399               FindOne<TQuery, TDefaultDocument>(query);
 400 
 401  
 402 
 403 这又是一个快捷方式:
 404 
 405               Find<TQuery, TDefaultDocument>(query).Limit(1).FirstOrDefault();
 406 
 407  
 408 
 409 瓦特 HICH是有用的,要知道,如果你认为可能有多个匹配的文件和要控制哪一个是返回。FirstOrDefault方法的MongoCursor下面 的例子 。
 410 
 411 要查询一个文件,是不是默认的文档类型使用FindOne <TQuery,的TDocument> 412 
 413 保存<TDocument>方法
 414 保存方法是插入和更新的组合。检查提供的文件,如果该文件是缺乏一个“_id”的元素,它假定这是一个新的文档和调用上的插入。如果该文件有一个“_id”的元素,它假定这可能是现有的文件,并调用Update就可以了,但以防万一,所以该文件将被插入,如果它不存在,将UPSERT标志。例如,您可以纠正错误使用的一本书的标题:
 415 
 416               BsonDocument query = new BsonDocument {
 417 
 418                             { “author”, “Kurt Vonnegut” }
 419 
 420                             { “title”, “Cats Craddle” }
 421 
 422               };
 423 
 424               BsonDocument book = books.FindOne(query);
 425 
 426               if (book != null) {
 427 
 428                             book[“title”] = “Cat’s Cradle”;
 429 
 430                             books.Save(book);
 431 
 432 }
 433 
 434  
 435 
 436 需要注意的是,我们的FindOne检查返回值,以确认它实际上找到了一个匹配的文档。
 437 
 438 更新<TQuery, TUpdate>方法
 439 更新方法用于更新现有的文件(见 下面的 UPSERT标志 )。的代码示例所示的保存方法也可以写为:
 440 
 441               BsonDocument query = new BsonDocument {
 442 
 443                             { “author”, “Kurt Vonnegut” }
 444 
 445                             { “title”, “Cats Craddle” }
 446 
 447               };
 448 
 449               BsonDocument update = new BsonDocument {
 450 
 451                             { “$set”, new BsonDocument(“title”, “Cat’s Cradle”) }
 452 
 453               };
 454 
 455               BsonDocument updatedBoook = books.Update(query, update);
 456 
 457  
 458 
 459 Update方法支持许多不同种类的更新文件,但再次,我们没有足够的空间来形容他们在本教程中。使用上面的例子中的“$集” 更新修饰符更新匹配的文件的一个元素的值。
 460 
 461 此外,还有一个过载的更新,使您可以指定一个或多个UpdateFlags。的值是和多UPSERT。 正常情况下,更新只影响一个文件,但使用UpdateFlags。多,你可以要求所有匹配的文件被更新。此外,指定UpdateFlags。UPSERT您可以要求的 更新文件被插入,如果无法找到符合条件的文件(注意,UPSERT功能需要更新文件是一个完整的文件,而不是在上面的示例中,只是一个更新操作)。
 462 
 463 计算方法
 464 有时候,你只需要知道一个集合有多少文件。 有两个版本的指望 。2-15 方法,首先计算所有的文件,和第二计数匹配的文件。例如:
 465 
 466               BsonDocument query = new BsonDocument {
 467 
 468                             { “author”, “Ernest Hemingway” }
 469 
 470               };
 471 
 472               int total = books..Count();
 473 
 474               int booksByHemingway = books.Count(query);
 475 
 476 删除方法
 477 可以使用此方法,从集合中删除文件。例如,要删除所有收集海明威的书,我们写的:
 478 
 479               BsonDocument query = new BsonDocument {
 480 
 481                             { “author”, “Ernest Hemingway” }
 482 
 483               };
 484 
 485               books.Remove(query);
 486 
 487  
 488 
 489 如果我们只是想删除一本书 - 海明威,我们可以这样写:
 490 
 491               BsonDocument query = new BsonDocument {
 492 
 493                             { “author”, “Ernest Hemingway” }
 494 
 495               };
 496 
 497               books.Remove(query, RemoveFlags.Single);
 498 
 499  
 500 
 501 虽然我们没有控制过这本书完全去除,但是这将是一个由海明威。
 502 
 503 RemoveAll方法
 504 如果你想删除一个集合中的所有文件,请使用:
 505 
 506               books.RemoveAll();
 507 
 508  
 509 
 510 请谨慎使用! RemoveAll只是一个快捷方式删除(空)。 也参看的DropCollection在MongoDatabase方法,这种方法虽然不同从 DropCollection中,只有数据被删除,而不是集合本身或任何索引。
 511 
 512 的CreateIndex方法
 513 此方法用于创建索引的集合。在其最简单的形式中,你只需要提供一个列表的元素名称被编入索引。还有更复杂的形式,使用一个 参数来指定要创建的索引的详细信息,但它们超出了本文的讨论范围。
 514 
 515 要建立索引的藏书作者,我们可以这样写:
 516 
 517               books.CreateIndex(“author”);
 518 
 519  
 520 
 521 注意,MongoDB是宽容的,如果您尝试创建一个索引已经存在,但要减少次数的服务器被要求创建相同的索引方法,而不是使用EnsureIndex。
 522 
 523 EnsureIndex方法
 524 您通常会调用此方法,而不是的CreateIndex。驱动跟踪的索引, 它 创造 了 只调用一次,每个索引(索引是否存在于服务器上,所以它必须调用的CreateIndex至少一次,以确保指数存在的驱动程序不知道)的CreateIndex。就像调用的CreateIndex调用EnsureIndex是:
 525 
 526               books.EnsureIndex(“author”);
 527 
 528  
 529 
 530 EnsureIndex也不能判断索引是否已被删除,因为它是在服务器上创建。你可以,知道任何索引的EnsureIndex忘记通过调用ResetIndexCache。被称为接下来的时间EnsureIndex的,它会调用的CreateIndex再次后,该指数将再次在索引缓存和createindex将不会被调用了该指数。
 531 
 532 不同的方法
 533 此方法用于对于一个给定的密钥,找到所有的不同的值。例如,要查找所有作者的藏书中,你可以这样写:
 534 
 535               IEnumerable<BsonValue> authors = books.Distinct(“author”);
 536 
 537               foreach (string author in authors) {
 538 
 539                             Console.WriteLine(author.AsString);
 540 
 541               }
 542 
 543  
 544 
 545 也有一个过载的不同的方法,该方法的查询,所以你可以找到不同的值,对于一个给定键的只是那些与查询匹配的文件。
 546 
 547 FindAndModify方法
 548 文本缺失。
 549 
 550 Group method
 551 文本缺失。
 552 
 553 MapReduce的方法
 554 文本缺失。
 555 
 556 MongoCursor <TQuery, TDocument> 557 找到方法(及其变化)不返回的实际结果的发现 。相反, 他们返回一个游标,可以列举出 检索结果的发现。该查询实际上并没有发送到服务器之前,我们 首先对试图枚举光标,这不仅意味着,查找方法不沟通与服务器(它们只返回一个游标)时,但我们可以控制的结果,通过改变光标之前列举的有用的方法。
 558 
 559 在C#中的 光标列举 了最便捷的方式 是使用foreach语句。但是,如果必要的话,你可以调用一个游标的的GetEnumerator方法和 工作直接用枚举。 您可以列举许多倍,你想一个光标。每次你调用GetEnumerator(通常是间接地通过foreach语句)一个新的查询发送到服务器。
 560 
 561 一旦你列举游标被冻结,并没有进一步的变化可以向它提出的。
 562 
 563 这个类的实例不是线程安全的。 然而,一旦光标被冻结,成为线程安全的枚举(请记住,每一次的GetEnumerator被称为一个单独的查询将被发送到服务器)。
 564 
 565 集合属性
 566 您可以使用此属性来定位光标集合查询。
 567 
 568 修改光标之前执行的方法
 569 在此类别的使用方法修改之前以某种方式被列举的光标控制游标返回的结果。请注意,所有这些方法都返回游标本身,让他们链接起来(“流利接口”)。
 570 
 571 Skip方法
 572 这种方法控制服务器应该跳过多少文件,然后返回结果。它往往是有用的分页,虽然是大值跳过知道,会变得非常低效的。例如,假设我们有很多由Isaac Asimov的书,想跳过第5:
 573 
 574               BsonDocument query = new BsonDocument {
 575 
 576                             { “author”, “Isaac Asimov” }
 577 
 578               };
 579 
 580               MongoCursor<BsonDocument> cursor = books.Find(query);
 581 
 582               foreach (BsonDocument book in cursor.Skip(5)) {
 583 
 584                             Console.WriteLine(book[“title”].AsString);
 585 
 586               }
 587 
 588 限制方法
 589 限制的方法可以让我们控制游标返回多少个文件 。此例子是类似于前一个,并告诉光标 返回至多10匹配文档:
 590 
 591               BsonDocument query = new BsonDocument {
 592 
 593                             { “author”, “Isaac Asimov” }
 594 
 595               };
 596 
 597               MongoCursor<BsonDocument> cursor = books.Find(query);
 598 
 599               foreach (BsonDocument book in cursor.Limit(10)) {
 600 
 601                             Console.WriteLine(book[“title”].AsString);
 602 
 603               }
 604 
 605  
 606 
 607 强制执行该限制是客户端,它是可能的服务器可能返回比需要更多的文件,在这种情况下,额外的将被忽略 。枚举中的某些值的查询发送到服务器,告诉它有多少文件发回的消息,但这些有时被视为暗示的服务器。对于小的范围内,你可以用一个负价值,让服务器知道在一个消息中返回所有的结果(实际限制 客户端将是负数的绝对值)。
 608 
 609 排序方法
 610 通常情况下,我们希望在一个特定的顺序返回结果。排序方法,让我们来告诉 服务器 , 什么样的顺序返回结果中。在其最简单的形式中,我们只需提供姓名的关键,我们要排序的结果,如:
 611 
 612               MongoCursor<BsonDocument> cursor = books.FindAll();
 613 
 614               foreach (BsonDocument book in cursor.Sort(“author”, “title”)) {
 615 
 616                             Console.WriteLine。
 617 
 618                                           “{0}: {1}”,
 619 
 620 book.[“author”].AsString,
 621 
 622 book.[“title”].AsString
 623 
 624 );
 625 
 626               }
 627 
 628  
 629 
 630 其他重载的排序方法让你单独控制每个键的排列顺序。
 631 
 632 其他光标修改方法
 633 改性方法有更多的光标不会在这里描述,但他们的名字就建议他们使用AddOption,批次,字段,标志,提示,和快照。
 634 
 635 触发列举的方法,
 636 下面的方法所有触发列举的光标。这意味着,必须先完成,光标使用上面的方法修改,光标前的枚举,并成为冻结。
 637 
 638 计算方法
 639 如果你不需要个别的结果,但只是想知道的计数匹配的文档,你可以使用此方法。这种方法相当于调用计数的收集。请注意,这种方法忽略任何跳过“或”限价已经设置光标(但看到“大小”的方法)。
 640 
 641 尺寸的方法
 642 这种方法是类似的计数方法,但任何荣誉跳过或限制已设置的选项上的光标。
 643 
 644 的GetEnumerator方法(或foreach语句)
 645 这种方法可以用来枚举 的结果 返回一个IEnumerator <TDocument>的 。通常你不会调用此方法,而是使用C#foreach语句来 枚举的结果。 请注意,实际与服务器的通信不会发生,直到 第一次的MoveNext方法被调用的枚举,但光标并成为冻结尽快的GetEnumerator被称为。
 646 
 647 FirstOrDefault方法
 648 有时,你只是想要或期望的一个结果,在这种情况下,您可以使用 此方法,这是更方便,比列举光标。在简单的情况下,你可能更喜欢,到使用FindOne方法MongoCollection的,但FirstOrDefault方法上的光标在检索一个文件,让你提供有趣的选项上的光标。例如,假设你想找到海明威出版的第一本书:
 649 
 650               BsonDocument query = new BsonDocument {
 651 
 652                             { “author”, “Ernest Hemingway” }
 653 
 654               };
 655 
 656               MongoCursor<BsonDocument> cursor = books.Find(query);
 657 
 658               cursor.Sort(“publicationDate”);
 659 
 660               BsonDocument firstBook = cursor.FirstOrDefault();
 661 
 662  
 663 
 664 因为游标的修改方法支持流畅的界面,你也可以链的召集中:
 665 
 666               BsonDocument query = new BsonDocument {
 667 
 668                             { “author”, “Ernest Hemingway” }
 669 
 670               };
 671 
 672               BsonDocument firstBook = books.Find(query)
 673 
 674                             .Sort(“publicationDate”)
 675 
 676                             .FirstOrDefault();
 677 
 678  
 679 
 680 FirstOrDefault实际上是一个IEnumerable的扩展方法,可以用一个MongoCursor,,因为MongoCursor <TQuery, TDocument>实现IEnumerable的<TDocument>的 。正因为如此,你可以使用任何IEnumerable的扩展方法与MongoCursor。
 681 
 682 ToArray方法
 683 这IEnumerable的扩展方法为您列举了光标,并返回一个数组的T.例如:
 684 
 685               BsonDocument query = new BsonDocument {
 686 
 687                             { “author”, “Ernest Hemingway” }
 688 
 689               };
 690 
 691               BsonDocument[] books = books.Find(query).ToArray();
 692 
 693  
 694 
 695 如果没有匹配的文档的返回值将是一个空数组,而不是C#空。
 696 
 697 ToList方法
 698 这IEnumerable的扩展方法为你列举了光标,并返回 列表 <T>的。例如:
 699 
 700               BsonDocument query = new BsonDocument {
 701 
 702                             { “author”, “Ernest Hemingway” }
 703 
 704               };
 705 
 706               List<BsonDocument> books = books.Find(query).ToList();
 707 
 708  
 709 
 710 如果没有匹配的文档的返回值将是一个空列表,而不是C#空。
 711 
 712 IEnumerable的扩展方法,触发枚举
 713 由于MongoCursor <TQuery, TDocument>实现IEnumerable <TDocument> 所有的为IEnumerable <T>的定义的扩展方法可以与MongoCursor使用,以及他们的大部分触发光标的枚举的。以下是一些比较常见的方法的列表:
 714 
 715 First
 716 FirstOrDefault
 717 Last
 718 LastOrDefault
 719 Single
 720 SingleOrDefault
 721 ToArray
 722 Tolist
 723 请记住,所有的扩展方法“看”的序列,当然列举的光标。另外要指出的是,一些IEnumerable的扩展方法具有相同的名称的方法 MongoCursor <TQuery, TDocument>,在这种情况下定义的方法,在MongoCursor <TQuery, TDocument>优先(除非你投您的光标移动到IEnumerable <TDocument>)。
 724 
 725 安全消耗光标的
 726 在列举上的光标触发一个连接从连接池获得,并不会被释放,直到它不再需要返回到连接池 。重要的 是 要确保枚举器得到一个机会释放连接,确保连接被返回到连接池 。实施的 一个MongoCursor的枚举释放连接,因为它可以(甚至可能的结果是在统计前完成)的连接丢失的可能性降至最低 。如果 枚举没有正确配置你的程序不会崩溃,但连接将不会被返回到连接池,将丢失(并且最终将被关闭,当它被垃圾回收),这将导致你的程序中打开连接数多于必要的。
 727 
 728 如果MongoCursor枚举消耗了所有的连接释放回连接池(其实,你可以肯定的,它会被退回尽快答复查询,或能获得更多产品信息就没有额外的结果)。
 729 
 730 确保连接被返回到连接池在所有情况下,关键是要保证Dispose方法调用的GetEnumerator返回的枚举。这是唯一真正的问题,如果你是消费手动枚举。所有的IEnumerable的扩展方法调用Dispose的枚举。C#foreach语句也可以保证在调用Dispose的枚举,因此,如果你坚持 IEnumerable的扩展方法和foreach语句,你将被罚款。
 731 
 732 说明方法
 733 此方法是从任何其他光标 方法 不同 ,因为它实际上并不返回查询的结果。相反,服务器返回的信息如何查询将被执行。这些信息可以是有用时,试图弄清楚为什么一个查询效果不理想。要使用此方法,你可以这样写:
 734 
 735               BsonDocument query = new BsonDocument {
 736 
 737                             { “author”, “Ernest Hemingway” }
 738 
 739               };
 740 
 741               MongoCursor<BsonDocument> cursor = books.Find(query);
 742 
 743               BsonDocument explanation = cursor.Explain();
 744 
 745 MongoGridFS类
 746 这个类是 C#GridFS规范将文件存储在MongoDB数据库 驱动程序 实现的。使用GridFS财产MongoDatabase,你通常会得到这个类的一个实例。
 747 
 748 这个类的实例是线程安全的。但是,如果你打算修改设置这种情况下,你应该做的,所以在多线程访问 的一个实例。
 749 
 750 数据库属性
 751 这个属性允许你来浏览,从实例MongoGridFS的数据库,它是与。
 752 
 753 设置属性
 754 此属性使您可以访问这种情况下的设置。您可以更改根目录名称GridFS集合(默认为“FS”)和DefaultChunkSize新的文件(默认为256KB)。需要注意的是缺省的块大小只适用于新的文件。不同的块尺寸与先前创建的任何文件将继续使用现有的块大小进行处理。这是不可能改变的块大小的文件,一旦它被创建。
 755 
 756 上传方法
 757 此方法上传的文件从客户端计算机的数据库。它总是GridFS文件系统中创建一个新的文件,所以,如果你上传的文件超过一次,将有多个版本的文件在数据库中。要使用此方法写:
 758 
 759               MongoGridFS gridFS = database.GridFS;
 760 
 761               MongoGridFSFileInfo的fileInfo = gridFS.Upload(“volcano.jpg”);
 762 
 763  
 764 
 765 上传的返回值是刚刚上传的文件的信息。如果你愿意,你可以忽略返回值。上传将抛出一个异常,如果它失败。
 766 
 767 有其他重载上传,让您指定不同的本地和远程的文件名,或者从一个流,而不是从一个文件直接上传。
 768 
 769 下载方式
 770 此方法下载一个文件,从数据库到客户端计算机。如果该文件已存在用户端电脑上,它会被覆盖。要使用此方法写:
 771 
 772               MongoGridFS gridFS = database.GridFS;
 773 
 774               gridFS.Download(“volcano.jpg”);
 775 
 776  
 777 
 778 正如前面提到的,可能有多个版本的相同的文件名在数据库中。缺省情况下,下载下载最新的版本(如所定义的“uploadDate”的文件的元数据的元素)。你可以下载一个不同的版本,提供一个完整版本参数。一个版本号的值可以是:
 779 
 780 1              The first version
 781 
 782 2              The second version
 783 
 784 n              The nth version
 785 
 786 -1              The newest version
 787 
 788 -2              The second newest version
 789 
 790 -n              The nth newest version
 791 
 792 0              Any version (not very useful unless there’s only one)
 793 
 794  
 795 
 796 因此,例如,检索最新版本的文件,你可以这样写:
 797 
 798               MongoGridFS gridFS = database.GridFS;
 799 
 800               gridFS.Download(“volcano.jpg”,-2); / /第二个版本
 801 
 802  
 803 
 804 其他的下载方法的重载让你指定不同的本地和远程的文件名,或者直接下载到一个流,而不是一个文件。
 805 
 806 查找方法
 807 Find方法查询GridFS文件系统的有关文件的信息。如果有一个以上的文件匹配 ,然后 将返回所有的信息(即使在提供特定的文件名 相同的文件名 可能有多个匹配,如果已上载超过一次)。例如:
 808 
 809               MongoGridFS gridFS = database.GridFS;
 810 
 811               IEnumerable<MongoGridFSFileInfo> files =
 812 
 813 gridFS.Find(“volcano.jpg”);
 814 
 815  
 816 
 817 如果没有相匹配的列表将是空的(不是C#NULL)。
 818 
 819 FindOne方法
 820 如果您希望只有一个匹配的文件名或愿意指定一个版本号的话,那就更方便的使用FindOne方法。例如:
 821 
 822               MongoGridFS gridFS = database.GridFS;
 823 
 824               MongoGridFSFileInfo file = gridFS.FindOne(“volcano.jpg”);
 825 
 826  
 827 
 828 或获得的第二个版本的文件信息:
 829 
 830               MongoGridFS gridFS = database.GridFS;
 831 
 832               MongoGridFSFileInfo file = gridFS.FindOne(“volcano.jpg”, 2);
 833 
 834  
 835 
 836 在这两种情况下,如果没有匹配的文件C#NULL被返回。
 837 
 838 Exists方法
 839 如果你只是想知道,如果该文件存在,但不需要任何的文件的元数据,你可以使用此方法。例如:
 840 
 841               MongoGridFS gridFS = database.GridFS;
 842 
 843               if (gridFS.Exists(“volcano.jpg”)) {
 844 
 845                             / /现在你知道该文件是否存在
 846 
 847               }
 848 
 849  
 850 
 851 删除方法
 852 该方法将删除从GridFS文件系统匹配的文件。如果有一个以上的文件匹配,他们都将被删除(见下面的示例中如何删除的文件只有一个版本)。例如:
 853 
 854               MongoGridFS gridFS = database.GridFS;
 855 
 856               gridFS.Delete(“volcano.jpg”);
 857 
 858  
 859 
 860 如果你只是想删除的最新版本写的东西一样:
 861 
 862               MongoGridFS gridFS = database.GridFS;
 863 
 864               MongoGridFSFileInfo的fileInfo = gridFS.FindOne(“volcano.jpg”,-2);
 865 
 866               if (fileInfo != null) {
 867 
 868                             gridFS.DeleteById(fileInfo.Id); / /删除_id
 869 
 870               }
 871 
 872 MongoGridFSFileInfo class
 873 这个类表示GridFS文件系统中存储的文件的信息。此类设计是类似的 。NET的FileInfo类的 POSS IBLE。
 874 
 875 ChunkSize property
 876 使用的块大小时,创建此文件。
 877 
 878 GridFS property
 879 您可以使用这个属性来导航从MongoGridFSFileInro实例的MongoGridFS它所属的对象。
 880 
 881 Id property
 882 此属性具有价值的“_id”元素这个文件。这个值是第一次上传文件时,分配,并保证是唯一的。 对于使用 C#驱动程序 上载的文件, 这将是一个ObjectID,虽然有可能你会遇到不同的驱动器上载的文件的ID可能是不同类型的。
 883 
 884 Length属性
 885 以字节为单位的文件的总长度。
 886 
 887 MD5 property
 888 该文件的MD5哈希计算在服务器上,当它被上传。
 889 
 890 Name属性
 891 远程GridFS文件系统中的文件的文件名。
 892 
 893 UploadDate财产
 894 该文件已被上传时的日期时间。这的DateTime是始终在UTC。
 895 
 896 即将实施的方法
 897 这个类还实现方法,返回一个流对象(流的一个子类),使您可以读取和写入GridFS文件相同的方式,做本地文件(一个可能的替代使用上传/下载方法,虽然可能没有那么快 )。这些方法都返回一个实例的MongoGridFSStream, 流的一个子类,支持读,写和S 伊克。,返回一个MongoGridFSStream的一个StreamWriter(或包裹着它的)的方法是:AppendText,创建,CreateText,打开,打开读取 ,OpenText,OpenWrite。
 898 
 899 安全模式类
 900 有好几次在本教程前面我们所提到的 安全模式。有各种级别的安全模式,并且这个类被用来 表示 这些级别。将SafeMode仅适用于不已经返回的值(因此,它并不适用于查询或命令)的操作。它适用于的方法MongoCollection:插入,删除,保存和更新。它也适用于到一个MongoGridFS的对象作为一个整体,使所有GridFS的操作都在相同的安全模式级别。
 901 
 902 安全模式的要点是后插入,删除,保存或更新信息发送到服务器后面是一个GetLastError函数命令使C#D 河可以确认操作成功。此外,当使用副本集,有SafeModes,让我们指定我们要等待多少次重复前完成GetLastError返回。进入安全模式 的值 的标准方法 是使用静态的类的属性和方法,如:
 903 
 904               SafeMode.False
 905 
 906               SafeMode.True
 907 
 908               SafeMode.WaitForReplications(n);
 909 
 910  
 911 
 912 的“n”的值包括伯,所以等待至少一个从已完成的复制,我们将使用“2”的值。
 913 
 914 我们也提到安全模式是继承了从服务器到数据库收集和操作。这种继承的时刻发生在创建相应的对象,但可以修改indepently 其后。因此,例如,如果我们 想要安全模式是在普通(默认是出于性能原因),但我们有一个集合,我们希望它被关闭,我们可以这样写:
 915 
 916               MongoServer server = MongoServer.Create(connectionString);
 917 
 918               server.SafeMode = SafeMode.True; // default to SafeMode.True
 919 
 920               MongoDatabase test = server[“test”]; // inherits SafeMode.True
 921 
 922 MongoCollection log = test[“log”]; // inherits SafeMode.True
 923 
 924               log.SafeMode = SafeMode.False; // turn off SafeMode for log
 925 
 926               BsonDocument importantMessage = new BsonDocument {
 927 
 928                             / /内容的重要信息
 929 
 930               };
 931 
 932 log.Insert(importantMessage, SafeMode.TRUE); / /覆盖安全模式
 933 
 934  
 935 
 936 代码的最后一行说明了安全模式,可以覆盖在个人的操作水平。
 937 
 938 第2部分:BSON图书馆
 939 本教程的其余部分是的BSON 图书馆。此库实现了序列化和反序列化BSON格式(我们将不包括)的数据中,还提供了一个BSON文档(我们将 ) 在内存中的表示 。的重要类BsonType,BsonValue(及其子类),BsonElement,BsonDocument和BsonArray。
 940 
 941 第1部分,其中有一个自上而下的结构不同,我们将在第2部分的的BSON库底检查后,开始对元素,文件和阵列类型和值,和工作。
 942 
 943 BsonType枚举
 944 BSON中的每个值都有一个类型,这是一个BSON支持一组固定的类型。以下列举列出了所有BSON支持的数据类型:
 945 
 946     public enum BsonType {
 947 
 948         Double = 0x01,
 949 
 950         String = 0x02,
 951 
 952         Document = 0x03,
 953 
 954         Array = 0x04,
 955 
 956         Binary = 0x05,
 957 
 958         ObjectId = 0x07,
 959 
 960         Boolean = 0x08,
 961 
 962         DateTime = 0x09,
 963 
 964         Null = 0x0a,
 965 
 966         RegularExpression = 0x0b,
 967 
 968         JavaScript = 0x0d,
 969 
 970         Symbol = 0x0e,
 971 
 972         JavaScriptWithScope = 0x0f,
 973 
 974         Int32 = 0x10,
 975 
 976         Timestamp = 0x11,
 977 
 978         Int64 = 0x12,
 979 
 980         MinKey = 0xff,
 981 
 982         MaxKey = 0x7f
 983 
 984 }
 985 
 986  
 987 
 988 我们将研究这些类型的更多细节,我们讨论BsonValues。
 989 
 990 BsonValue类
 991 这是一个抽象类,它代表一个类型的BSON值的概念。有一个子类BsonValue的每一个 值 在 BsonType枚举。BsonValue定义一些属性和方法是共同所有 BSON类型(或在某些情况下,将其转换从BsonValue到一些它的子类或。NET类型)。
 992 
 993 ,因为BsonValue是一个抽象类,不能构造这个类的实例,你只能构建其具体子类的实例。另一方面,你经常会看到这种类型的变量,参数和返回值。
 994 
 995 创建BsonValues
 996 有几种方法来创建实例BsonValues(所有):
 997 
 998 1.       使用静态创建方法BsonValue
 999 
1000 2. 使用的一个的BsonValue子类的静态Create方法
1001 
1002 3利用隐式转换。NET类型的BsonValue
1003 
1004 4:的BsonValue子类调用公共的构造函数(如果有的话)
1005 
1006 所有的BsonValue子类有一个静态的创建方法。我们鼓励您使用的静态Create方法,使子类可以处理特殊情况的要求(通常返回常用值预先创建的对象的一个实例,以避免造成不必要的对象)。在某些情况下,有没有公共的构造函数,你必须使用静态创建方法。
1007 
1008 BsonType财产
1009 这个属性可以用来确定实际的的 BsonValue 类型 。当然,你可以使用实际的类的对象做同样的事情,但它往往是更方便,速度更快,使用此属性。下面的例子显示了 几种方法:
1010 
1011               BsonValue value;
1012 
1013               if (value.BsonType == BsonType.INT32)
1014 
1015                             / /我们知道的值是一个实例BsonInt32
1016 
1017               }
1018 
1019               if (value is BsonInt32) {
1020 
1021                             / /另一种方式告诉该值是一个BsonInt32
1022 
1023               }
1024 
1025               if (value.IsInt32) {
1026 
1027                             / /最简单的方法,告诉该值是一个BsonInt32
1028 
1029               }
1030 
1031  
1032 
1033 另请参阅[类型]最便捷的方式来测试,如果值是一个特定类型的属性。
1034 
1035 [类型]属性
1036 BsonValue定义一些属性,可用于沮丧的一个BsonValue一个具体的类型。的结果[类型]属性的一个子类的BsonValue或在适当的时候。NET的原始值。作为[类型]属性的完整列表是:
1037 
1038               AsBoolean (bool)
1039 
1040               AsBsonArray
1041 
1042               AsBsonBinaryData
1043 
1044               AsBsonDocument
1045 
1046               AsBsonJavaScript / /也可以,如果BsonType == JavaScriptWithScope
1047 
1048               AsBsonJavaScriptWithScope
1049 
1050               AsBsonMaxKey
1051 
1052               AsBsonMinKey
1053 
1054               AsBsonNull
1055 
1056               AsBsonRegularExpression
1057 
1058               AsBsonSymbol
1059 
1060               AsBsonTimestamp
1061 
1062               AsByteArray
1063 
1064               AsDateTime (DateTime)
1065 
1066               AsDouble (double)
1067 
1068               AsGuid (Guid)
1069 
1070               AsInt32 (int)
1071 
1072               AsInt64 (long)
1073 
1074               AsObjectId
1075 
1076               AsString (string)
1077 
1078  
1079 
1080 的回报。NET基本类型的属性后,他们在上面的列表中,括号中的一个。NET类型的。
1081 
1082 所有这些属性抛出一个InvalidCastException,如果实际类型的BsonValue是不是必需的。如果你不确定类型 的BsonValue,你可以事先测试使用的是[类型]属性如下所述。
1083 
1084 AsBsonJavaScript是一个特殊的情况下,即使成功,因为它的实际类型的价值是BsonJavaScriptWithScope的,因为BsonJavaScriptWithScope是一个子类,BsonJavaScript。
1085 
1086 [类型]属性,它可以将某些类型之间的更为有限。
1087 
1088 [类型]属性
1089 BsonValue定义一些属性,可以用来查询特定类型的一个实例BsonValue。这些便利,让你写的更紧凑的代码。例如:
1090 
1091               if (value.IsString) {
1092 
1093                             / /我们知道的值是一个实例BsonString
1094 
1095                             / /我们也知道价值。AsString不会失败
1096 
1097               }
1098 
1099  
1100 
1101 的完整列表[类型]属性是:
1102 
1103               IsBoolean
1104 
1105 IsBsonArray
1106 
1107               IsBsonBinaryData
1108 
1109               IsBsonDocument
1110 
1111               IsBsonJavaScript
1112 
1113               IsBsonJavaScriptWithCode
1114 
1115               IsBsonMaxKey
1116 
1117               IsBsonMinKey
1118 
1119               IsBsonNull
1120 
1121 IsBsonRegularExpression
1122 
1123               IsBsonSymbol
1124 
1125 IsBsonTimestamp
1126 
1127 IsDateTime
1128 
1129 IsDouble
1130 
1131 IsGuid
1132 
1133 IsInt32
1134 
1135 IsInt64
1136 
1137               IsObjectId
1138 
1139               ISSTRING
1140 
1141 [类型]的方法
1142 BsonValue提供了一些方法 ,可以进行有限的类型之间的转换。这些转换的,在大多数情况下是安全的,被预期不会失败。在[类型]的 方法是:
1143 
1144               ToBoolean
1145 
1146               ToDouble
1147 
1148               ToInt32
1149 
1150               ToInt64
1151 
1152  
1153 
1154 ToBoolean方法 永远不会失败。它使用JavaScript定义2006:。2006年:内感真相,假,00.0,南,BsonNull和“是假的,一切是”真“(包括字符串”假“!)。
1155 
1156 ToBoolean方法 是非常有用的,当你正在处理的文件有不一致的方式记录true / false值。例如:
1157 
1158               if (employee[“ismanager”].ToBoolean()){
1159 
1160                             / /我们知道员工是经理
1161 
1162                             / /即使价值有时是正确的,有时1
1163 
1164               }
1165 
1166  
1167 
1168 将工作,即使混合使用的文件类型 代表true / false值。相比之下,AsBoolean的属性将只 当值被记录下来使用严格BsonBoolean值。
1169 
1170 ToDouble,ToInt32犯法,ToInt64方法将失败,如果转换之间的数值类型(虽然可能会被截断值!)。如果转换的一些目标类型,如果该字符串可以被解析为一个字符串,他们会取得成功 ,否则,抛出一个异常。
1171 
1172 创建方法
1173 虽然你不能创建实例BsonValue,在BsonValue类有一个 静态方法调用创建,你可以用它来 创建具体的实例BsonValue。在运行时的基础上提供的值的实际类型 决定所产生的BsonValue。A N 异常被抛出,如果提供的价值不能被映射到一个BsonValue。例如:
1174 
1175               BsonValue value = BsonValue.Create(1); // creates a BsonInt32
1176 
1177               BsonValue value = BsonValue.Create(1.0); // creates a BsonDouble
1178 
1179               BsonValue value = BsonValue.Create(“abc”); // a BsonString
1180 
1181  
1182 
1183 如果你想选择的BsonValue类型,使用的子类BsonValue,而不是一个静态的创建方法:
1184 
1185               BsonDouble value = BsonDouble.Create(1);
1186 
1187               BsonJavaScript value = BsonJavaScript.Create(“this.a == 4”);
1188 
1189               BsonSymbol value = BsonSymbol.Create(“+”);
1190 
1191  
1192 
1193 在第一种情况将创建一个BsonDouble,和int值将被转换为双精度值1.0。在第二个例子将创建一个BsonJavaScript,编码值将是“this.a == 4”。在第三种情况下将创建一个BsonSymbol的“+”定定地看着在BsonSymbolTable的。 如果提供的值不能转换为需要的类型的BsonValue子类抛出一个异常。
1194 
1195 。NET类型的隐式转换BsonValue
1196 BsonValue类还定义了一些隐式转换BsonValue的。这使得它非常容易地创建BsonValues。下面是一些例子:
1197 
1198               BsonValue value = 1; // converts 1 to a BsonInt32
1199 
1200               BsonValue value = 1.0; // converts 1.0 to a BsonDouble
1201 
1202               BsonValue value = “abc”; // converts “abc” to a BsonString
1203 
1204  
1205 
1206 这些隐式转换是特别方便。NET值作为参数调用函数时,采取BsonValue的一个参数,允许你使用原始 。这些隐式转换的一个重要优势是映射。NET类型的 匹配 BsonType,发生在编译的时候,这样的创作是非常快的BsonValues。也有非常小的开销的事实是,我们 正在创建一个实例BsonValue,因为如果我们不使用BsonValue和使用的对象,而不是 所有的原始。NET值将不得不盒装的。从本质上讲,BsonValue就是我们的方式拳。NET类型(但我们的方法,我们得到,以标记值与BsonType的和我们得到了很多有用的属性和方法定义)。
1207 
1208 下列隐式转换定义如下:
1209 
1210 NET类型。
1211 
1212 BsonType
1213 
1214 bool
1215 
1216 Boolean
1217 
1218 byte[]
1219 
1220 Binary (subtype Binary)
1221 
1222 DateTime
1223 
1224 DateTime
1225 
1226 double
1227 
1228 Double
1229 
1230 GUID
1231 
1232 Binary (subtype Uuid)
1233 
1234 int
1235 
1236 Int32
1237 
1238 long
1239 
1240 Int64
1241 
1242 Regex
1243 
1244 RegularExpression
1245 
1246 string(字符串)
1247 
1248 String
1249 
1250  
1251 
1252 隐式转换的列表是相当短的目的。我们只定义了隐式转换的情况下,有一个完全匹配的。NET类型和相应的BsonType,其中有可以不丢失信息的转换。
1253 
1254 从BsonValue。NET类型的显式转换
1255 作为一种替代[类型]属性BsonValue类也定义了一组明确一些。NET原始类型的转换。例如,下面的两个语句是等价的:
1256 
1257               int age = person[“age”].AsInt32;
1258 
1259 int age = (int) person[“age”];
1260 
1261  
1262 
1263 所提供的显式转换的一组是完全相反的组提供的隐式转换,所以在上一节的表可以读取由右至左,以寻找可用的显式转换。
1264 
1265 你可以使用任何你喜欢的,但 由于[类型]的方法往往更具可读性。考虑这些:
1266 
1267               string zip = person[“address”].AsBsonDocument[“zip”].AsString;
1268 
1269               string zip = (string) ((BsonDocument) person[“address”])[“zip”];
1270 
1271  
1272 
1273 在第二种形式中,你学会更好地得到所有这些括号恰到好处!
1274 
1275 Equals和GetHashCode方法 (和运算符==和!=1276 的BsonValue类的所有重载equals和GetHashCode的因此,BsonValue的情况下,安全使用字典中的键。
1277 
1278 BsonValue子类
1279 前面我们提到过,有一个子类BsonValue每BsonType。下面是的完整列表BsonValue子类:
1280 
1281               BsonArray
1282 
1283               BsonBinaryData
1284 
1285               BsonBoolean
1286 
1287               BsonDateTime
1288 
1289               BsonDocument
1290 
1291               BsonDouble
1292 
1293               BsonInt32
1294 
1295               BsonInt64
1296 
1297               BsonJavaScript
1298 
1299               BsonJavaScriptWithScope
1300 
1301               BsonMaxKey
1302 
1303               BsonMinKey
1304 
1305               BsonObjectId
1306 
1307               BsonRegularExpression
1308 
1309               BsonString
1310 
1311               BsonSymbol
1312 
1313               BsonTimestamp
1314 
1315  
1316 
1317 我们将讨论这些子类的简单地说,离开BsonDocument BsonArray的结束,因为他们是最复杂的。
1318 
1319 BsonBinaryData类
1320 这个类持有BSON类型 的二进制 值 。它具有 以下的属性和方法(除了继承自BsonValue):
1321 
1322               BsonBinaryData(byte[] bytes)
1323 
1324               BsonBinaryData(byte[] bytes, BsonBinarySubType subType)
1325 
1326               BsonBinaryData(GUID GUID)
1327 
1328               byte[] Bytes
1329 
1330               BsonBinarySubType SubType
1331 
1332               implicit conversion from byte[]
1333 
1334               implicit conversion from Guid
1335 
1336               static BsonBinaryData Create(byte[] bytes)
1337 
1338               static BsonBinaryData Create(byte[] bytes,
1339 
1340                             BsonBinarySubType subType)
1341 
1342               static BsonBinaryData Create(Guid guid)
1343 
1344               static BsonBinaryData Create(object value)
1345 
1346               Guid ToGuid()
1347 
1348 BsonBoolean类
1349 这个类包含的BSON类型 布尔 值 。它 具有以下的属性和方法(除了继承自BsonValue):
1350 
1351               BsonBoolean(bool value)
1352 
1353               static BsonBoolean False
1354 
1355               static BsonBoolean True
1356 
1357               object RawValue
1358 
1359               bool Value
1360 
1361               implicit conversion from bool
1362 
1363               static BsonBoolean Create(bool value)
1364 
1365               static BsonBoolean Create(object value)
1366 
1367  
1368 
1369 这个类有一些预先创建的实例(FALSE,TRUE)。您可以使用他们自己,和Create方法返回他们在适当的时候。
1370 
1371 BsonDateTime类
1372 这个类持有BSON DateTime类型的值。它 具有以下的属性和方法(除了继承自BsonValue):
1373 
1374               BsonDateTime(DateTime value)
1375 
1376               object RawValue
1377 
1378               DateTime Value
1379 
1380               implicit conversion from DateTime
1381 
1382               static BsonDateTime Create(DateTime value)
1383 
1384               static BsonDateTime Create(object value)
1385 
1386  
1387 
1388 需要注意的是BSON DateTime值始终在UTC。
1389 
1390 BsonDouble类
1391 这个类持有BSON类型双值。它 具有以下的属性和方法(除了继承自BsonValue):
1392 
1393               BsonDouble(double value)
1394 
1395               object RawValue
1396 
1397               double Value
1398 
1399               implicit conversion from double
1400 
1401               static BsonDouble Create(double value)
1402 
1403               static BsonDouble Create(object value)
1404 
1405 BsonInt32类
1406 这个类持有BSON Int32类型的值。它 具有以下的属性和方法(除了继承自BsonValue):
1407 
1408               BsonInt32(int value)
1409 
1410               static BsonInt32 MinusOne
1411 
1412               static BsonInt32 Zero
1413 
1414               static BsonInt32 One
1415 
1416               static BsonInt32 Two
1417 
1418               static BsonInt32 Three
1419 
1420               object RawValue
1421 
1422               int Value
1423 
1424               implicit conversion from int
1425 
1426               static BsonInt32 Create(int value)
1427 
1428               static BsonInt32 Create(object value)
1429 
1430  
1431 
1432 这个类有一些预先创建的实例(MinusOne,零,一,二,三)。静态创建方法将返回他们在适当的时候。
1433 
1434 BsonInt64类
1435 此类包含BSON类型的Int64值。它 具有以下的属性和方法(除了继承自BsonValue):
1436 
1437               BsonInt64(long value)
1438 
1439               object RawValue
1440 
1441               long Value
1442 
1443               implicit conversion from long
1444 
1445               static BsonInt64 Create(long value)
1446 
1447               static BsonInt64 Create(object value)
1448 
1449 BsonJavaScript类
1450 这个类拥有的BSON JavaScript类型的值。它 具有以下的属性和方法(除了继承自BsonValue):
1451 
1452               BsonJavaScript(string code)
1453 
1454               object RawValue
1455 
1456               string Code
1457 
1458               implicit conversion from string
1459 
1460               static BsonBinaryData Create(object value)
1461 
1462               static BsonJavaScript Create(string code)
1463 
1464 BsonJavaScriptWithScope类
1465 这个类包含值BSON类型JavaScriptScope的。它 具有以下的属性和方法(除了继承自BsonValue):
1466 
1467               BsonJavaScriptWithScope(string code, BsonDocument scope)
1468 
1469               string Code // inherited from BsonJavaScript
1470 
1471               BsonDocument Scope
1472 
1473               static BsonJavaScriptWithScope Create(object value)
1474 
1475               static BsonJavaScriptWithScope Create(string code,
1476 
1477                             BsonDocument scope)
1478 
1479  
1480 
1481 请注意,BsonJavaScriptWithScope是一个子类的BsonJavaScript。
1482 
1483 BsonMaxKey类
1484 这个类持有单一值BSON类型MaxKey的。它 具有以下的属性和方法(除了继承自BsonValue):
1485 
1486               static BsonMaxKey Singleton // can use Bson.MaxKey instead
1487 
1488  
1489 
1490 请注意,这个类实现独立的,并因此它只有一个实例存在。您可以在你的代码中访问此单一值在两个方面:
1491 
1492               BsonMaxKey mk = BsonMaxKey.Singleton;
1493 
1494               BsonMaxKey mk = Bson.MaxKey / /更方便
1495 
1496 BsonMinKey类
1497 这个类持有单一值BSON类型MinKey的。它 具有以下的属性和方法(除了继承自BsonValue):
1498 
1499               static BsonMinKey Singleton // can use Bson.MinKey instead
1500 
1501  
1502 
1503 请注意,这个类实现独立的,并因此它只有一个实例存在。您可以在你的代码中访问此单一值在两个方面:
1504 
1505               BsonMinKey mk = BsonMinKey.Singleton;
1506 
1507               BsonMinKey mk = Bson.MinKey / /更方便
1508 
1509  
1510 
1511 BsonNull类
1512 这个类包含的单身BSON类型的空值。它 具有以下的属性和方法(除了继承自BsonValue):
1513 
1514               static BsonNull Singleton // can use Bson.Null instead
1515 
1516  
1517 
1518 请注意,这个类实现独立的,并因此它只有一个实例存在。您可以在你的代码中访问此单一值在两个方面:
1519 
1520               BsonNull n = BsonNull. // Singleton
1521 
1522               BsonNull n = Bson.NULL; / /更方便
1523 
1524  
1525 
1526 注意,也有BsonElement永远不会有一个C#NULL作为它的值,取而代之的是BsonNull单身是用来表示的BSON空值。
1527 
1528 BsonObjectId类
1529 这个类包含的值BSON类型的ObjectId的 。它 具有以下的属性和方法(除了继承自BsonValue):
1530 
1531               BsonObjectId(byte[] bytes) // must be exactly 12 bytes
1532 
1533               BsonObjectId(int timestamp, long machinePidIncrement)
1534 
1535               BsonObjectId(ObjectId value)
1536 
1537               BsonObjectId(string value)
1538 
1539               int Timestamp // first 4 bytes of ObjectId
1540 
1541               long MachinePidIncrement // last 8 bytes of ObjectId
1542 
1543               int Machine
1544 
1545               int Pid
1546 
1547               int Increment
1548 
1549               object RawValue
1550 
1551               ObjectId Value
1552 
1553               DateTime CreationTime // derived from Timestamp
1554 
1555               implicit conversion from ObjectId
1556 
1557               static BsonObjectId Create(byte[] bytes)
1558 
1559               static BsonObjectId Create(int timestamp,
1560 
1561 long machinePidIncrement)
1562 
1563               static BsonObjectId Create(object value)
1564 
1565               static BsonObjectId Create(ObjectId value)
1566 
1567               static BsonObjectId Create(string value)
1568 
1569               static BsonObjectId GenerateNewId()
1570 
1571               static BsonObjectId Parse(string value)
1572 
1573               static bool TryParse(string value, out BsonObjectId objectId)
1574 
1575               byte[] ToByteArray()
1576 
1577  
1578 
1579 的ObjectId结构在下一节。之间的差异BsonObjectId和OBJECTID是BsonObjectId是一个子类,BsonValue可以的BsonElement的价值,而objectid是一个结构和包含的实际 物理表示一个ObjectID(这样的Value属性的BsonObjectId类型的ObjectId)。 的ObjectID的属性回荡在BsonObjectId,只需调用底层的ObjectId属性。
1580 
1581 OBJECTID STRUCT
1582 这个结构持有一个 ObjectID的物理表示 。它具有以下 的属性和方法:
1583 
1584               ObjectId(byte[] bytes) // must be exactly 12 bytes
1585 
1586               ObjectId(int timestamp, long machinePidIncrement)
1587 
1588               ObjectId(string value)
1589 
1590               int Timestamp // first 4 bytes of ObjectId
1591 
1592               long MachinePidIncrement // last 8 bytes of ObjectId
1593 
1594               int Machine
1595 
1596               int Pid
1597 
1598               int Increment
1599 
1600               DateTime CreationTime // derived from Timestamp
1601 
1602               static ObjectId GenerateNewId()
1603 
1604               static ObjectId Parse(string value)
1605 
1606               static bool TryParse(string value, out ObjectId objectId)
1607 
1608               byte[] ToByteArray()
1609 
1610 BsonRegularExpression类
1611 此类包含BSON类型正则表达式的值。它 具有以下的属性和方法(除了继承自BsonValue):
1612 
1613               BsonRegularExpression(string pattern) // options == “”
1614 
1615               BsonRegularExpression(string pattern, string options)
1616 
1617               BsonRegularExpression(Regex regex)
1618 
1619               string Pattern
1620 
1621               string Options
1622 
1623               implicit conversion from Regex
1624 
1625               implicit conversion from string
1626 
1627               static BsonRegularExpression Create(object value)
1628 
1629               static BsonRegularExpression Create(string pattern)
1630 
1631               static BsonRegularExpression Create(string pattern,
1632 
1633 string options)
1634 
1635               static BsonRegularExpression Create(Regex regex)
1636 
1637               Regex ToRegex()
1638 
1639 BsonString类
1640 这个类持有BSON String类型的值。它 具有以下的属性和方法(除了继承自BsonValue):
1641 
1642               BsonString (string value)
1643 
1644               static BsonString Empty
1645 
1646               object RawValue
1647 
1648               string Value
1649 
1650               implicit conversion from string
1651 
1652               static BsonString Create(object value)
1653 
1654               static BsonString Create(string value)
1655 
1656  
1657 
1658 这个类有一个预先创建的实例(空)。您可以使用它自己的Create方法返回在适当的时候。
1659 
1660 BsonSymbol类
1661 这个类持有BSON类型符号的值。它 具有以下的属性和方法(除了继承自BsonValue):
1662 
1663               string Name
1664 
1665               implicit conversion from string
1666 
1667               static BsonSymbol Create(object value)
1668 
1669               static BsonSymbol Create(string name)
1670 
1671  
1672 
1673 这个类没有一个公共的构造函数,因为BsonSymbols保证是唯一的,因此你必须使用静态Create方法,而不是(它看起来的BsonSymbol的BsonSymbolTable和创建一个新的的实例BsonSymbol仅在必要时)。
1674 
1675 BsonTimestamp类
1676 这个类持有的BSON Timestamp类型的值。它 具有以下的属性和方法(除了继承自BsonValue):
1677 
1678               BsonTimestamp(int timestamp, int increment)
1679 
1680 BsonTimestamp(long value)
1681 
1682               object RawValue
1683 
1684               long Value
1685 
1686               int Timestamp // high order 32 bits of Value
1687 
1688               int Increment // low order 32 bits of Value
1689 
1690               implicit conversion from long
1691 
1692               static BsonTimestamp Create(int timestamp, int increment)
1693 
1694               static BsonTimestamp Create(long value)
1695 
1696               static BsonTimestamp Create(object value)
1697 
1698 BsonElement类
1699 这个类表示的BSON元素 的名称/值对的 实例 。它是什么BsonDocuments包含(不像BsonArrays,其中包含BsonValues)。这是一个非常简单的类,包含以下方法和属性:
1700 
1701               BsonElement(string name, BsonValue value)
1702 
1703               string Name
1704 
1705               BsonValue Value
1706 
1707               static BsonElement Create(string name, BsonValue value)
1708 
1709               static BsonElement Create(bool condition, string name,
1710 
1711                             BsonValue值)
1712 
1713              
1714 
1715 你可能不会有明确地建立BsonElement,很多时候,他们就越有可能将创建自动为您调用的Add方法BsonDocument之一当你。
1716 
1717 静态创建方法的返回值是C#空C#空(或者,如果条件为假)。
1718 
1719 需要注意的是BsonElement实现Equals和GetHashCode,所以BsonElements的,可以作为字典键。
1720 
1721 BsonDocument类
1722 这个类是C#驱动程序的主力 。您将使用了很多!因为它是用来这么多的接口是有点复杂的,以提供许多常见的用例。基本上有三种方式创建和填充BsonDocument的:
1723 
1724 1.       创建一个新的文件,并调用添加和设置方法
1725 
1726 2. 创建一个新的文件,并使用C#集合初始化器的语法
1727 
1728 3创建一个新的文件,并使用流畅的界面风格,支持添加和设置
1729 
1730 首先是简单,易于使用,但第二,要求您要熟悉与集合初始化器的语法,更具有可读性和推荐的方法是创建BsonDocuments。
1731 
1732 BsonDocument构造函数
1733 您可以使用BsonDocument的构造函数来创建一个空的BsonDocument或作为一个简单 的方法来创建一个单一的元素BsonDocument。所有重载BsonDocument(有两个例外),只是简单的调用提供的参数匹配的Add方法。
1734 
1735 ,要创建一个空BsonDocument的写:
1736 
1737               BsonDocument document = new BsonDocument();
1738 
1739  
1740 
1741 要创建一个文档填充一个元素写:
1742 
1743               BsonDocument query = new BsonDocument(“author”, “Hemmingway”);
1744 
1745  
1746 
1747 默认情况下,BsonDocument不重复的元素名称,如果您尝试添加一个元素与现有名称抛出一个异常。如果你想允许重复的元素的名称,您必须使用下面的构造函数:
1748 
1749               BsonDocument document = new BsonDocument(true); // allow dups
1750 
1751               document.Add(“hobby”, “hiking”);
1752 
1753               document.Add(“hobby”, “cycling”); // only acessible via index
1754 
1755               BsonValue h1 = document[“hobby”]; // returns “hiking”
1756 
1757               BsonValue h2 = document[0]; // also returns “hiking”
1758 
1759               BsonValue h3 = document[1]; // returns “cycling”
1760 
1761  
1762 
1763 也有过载的BsonDocument的构造函数,它接受一个:
1764 
1765 BsonElement
1766 IDictionary<string, object>
1767 IEnumerable<BsonElement>
1768 params BsonElement[]
1769 请参阅相应的Add方法的说明,每一个。
1770 
1771 BsonDocument构造函数与集合初始化器的语法
1772 这是首选的方式来创建和填充BsonDocuments,(除单元素文件的 名称和值 传递 给构造函数 更容易地创建 )。C#集合初始化器语法的工作方式是,它可以让你提供的值的列表(可以是元组),被 传递到一个匹配的Add方法 。简单的编译器将调用 匹配 的 Add方法 。许多中创建示例代码,您见过这么远的BsonDocuments使用此语法。例如:
1773 
1774               BsonDocument book = new BsonDocument {
1775 
1776                             { “author”, “Ernest Hemingway” },
1777 
1778                             { “title”, “For Whom the Bell Tolls” }
1779 
1780               };
1781 
1782  
1783 
1784 由编译器被转换为以下:
1785 
1786               BsonDocument book = new BsonDocument();
1787 
1788               book.Add(“author”, “Ernest Hemingway”);
1789 
1790               book.Add(“title”, “For Whom the Bell Tolls”);
1791 
1792  
1793 
1794 这两者是完全等效的,但首先是更加优雅和可读性,因为它反映了结构的BsonDocument正在创建更加简洁。
1795 
1796 使用集合初始化器的语法时,一个常见的错误是忘记了一个括号套。这不起作用的原因是明显的,当我们看到,编译器将其转换:
1797 
1798               BsonDocument wrong = new BsonDocument { “name”, “value” };
1799 
1800  
1801 
1802 到:
1803 
1804               BsonDocument wrong = new BsonDocument();
1805 
1806 错误。添加NAME
1807 
1808 错误。扩大广告价值。
1809 
1810  
1811 
1812 编译时错误,因为没有相匹配的签名(幸好)的Add方法。
1813 
1814 BsonDocument构造函数用流利的接口方法
1815 到构建一个BsonDocument的另一种方式是使用流畅的界面风格Add方法来填充文件。例如:
1816 
1817               BsonDocument book = new BsonDocument()
1818 
1819                             .Add(“author”, “Ernest Hemingway”)
1820 
1821                             .Add(“title”, “For Whom the Bell Tolls”);
1822 
1823  
1824 
1825 我们并不网友的这种风格,因为我们觉得C#集合初始化器的语法是优越的,但如果你从另一个驱动程序的移植代码,你会发现这种风格有用的。
1826 
1827 AllowDuplicateNames财产
1828 确定该文件是否被允许包含重复的名称或。BSON标准规定,重复的名字是不允许的,但在某些情况下,它可能是有用的(例如,当一个XML文档映射到BsonDocument)。
1829 
1830 Count属性
1831 此属性返回该文件包含的元素的数量。
1832 
1833 元素属性
1834 此属性返回一个可用于列举了文档的元素的IEnumerable的<BsonElement>值。您也可以枚举元素在一个BsonDocument的直接(不使用元素属性)因为 BsonDocument 实现了IEnumerable <BsonElement>。的名字也,价值观和RawValues的性能。
1835 
1836 名称属性
1837 此属性返回的IEnumerable的<String>的值,可以用来列举了文档的元素的名称。
1838 
1839 RawValues财产
1840 该属性返回一个的IEnumerable的<OBJECT>值,可以用来列举了为原料的对象(而不是所有BsonValues的原始值,布尔,日期时间,双,INT32,的Int64,String和时间戳的文件的元素的值这样做)。返回的序列包含C#空为任何BsonValue的 s的类型,没有RawValue。
1841 
1842 Values属性
1843 此属性返回一个枚举的值的的文件,BsonValues的元素,可用于的IEnumerable的<BsonValue>值。
1844 
1845 添加方法
1846 有很多重载的Add方法。请注意,在所有情况下,C#空值将被忽略,所以你就不必把if语句添加在你的电话,以检查是否你的价值是空的(假设你希望它被忽略)。当 一个Add方法传递一个C#空值,它根本什么都不做。
1847 
1848 添加(BsonElement)方法
1849 这是基本的Add方法。所有其他的Add方法调用这一个。此方法的行为略有不同,具体取决于是否允许重复的元素名称或没有。如果重复的名字是不允许的元素具有相同的名称存在,则抛出一个异常,否则它被添加到集合末尾,并且只能通过索引访问(访问将返回现有的元素,而不是新的名字1)。
1850 
1851 添加方法(IEnumerable的<BsonElement>1852 这个方法只是简单地调用的添加(BsonElement)的每个元素传递的。
1853 
1854 添加(名称,值)的方法
1855 此方法创建和一个BsonElement添加到文档中,如果提供的值是C#空 。例如:
1856 
1857               BsonDocument book = new BsonDocument();
1858 
1859               book.Add(“author”, “Ernest Hemingway”);
1860 
1861  
1862 
1863 由于这Add方法将其参数直接通过的BsonElement构造,你可以参考下面的讨论中有关创建BsonElements的和。NET提供的价值映射到一个BsonValue的。
1864 
1865 重要的是要记住,Add方法不执行任何操作,如果该值suplied是一个C#空。如果你想一个BSON的NULL被存储为一个缺失值,您必须提供的BSON空值自己。一个方便的方式做到这一点是使用C#的空合并运算符:
1866 
1867               BsonDocument book = new BsonDocument {
1868 
1869                             { “author”, author ?? Bson.Null }
1870 
1871               };
1872 
1873 添加方法(条件,名称,值)
1874 此方法创建并添加了一个新的BsonElement的文件,如果条件为真时提供的值是C#空 。这种方法的存在是为了支持有条件地将元素添加到文档时,使用C#集合初始化器的语法。例如:
1875 
1876               BsonDocument book = new BsonDocument {
1877 
1878                             { “author”, “Ernest Hemingway” },
1879 
1880                             { “title”, “For Whom the Bell Tolls” },
1881 
1882                             {havePublicationDate,“publicationDate”,publicationDate}
1883 
1884               };
1885 
1886  
1887 
1888 这是唯一真正必要的结构值(因为它们不能被C#NULL)。例如,假设您只是想添加的“字幕”元素,如果它不是C#空。我们可以简单的写:
1889 
1890               BsonDocument book = new BsonDocument {
1891 
1892                             { “author”, “Ernest Hemingway” },
1893 
1894                             { “title”, “For Whom the Bell Tolls” },
1895 
1896                             { “subtitle”, subTitle }
1897 
1898               };
1899 
1900              
1901 
1902 如果该值的副标题是C#空“字幕”元素将被添加到文档中。
1903 
1904 添加方法(IEnumerable的<BsonElement>1905 每一个元素将被添加这BsonDocument。需要注意的是不被复制的元素。
1906 
1907 由于BsonDocument实现了IEnumerable <BsonElement>,你可以传递一个的实例BsonDocument这种方法。然而,由于该元素不被克隆,相同的BsonElements是在两个BsonDocuments的。这意味着,如果你改变了价值的BsonElement在一个文档中,它会改变其他。如果你不希望这种行为,那么你之前,必须复制的元素添加到 文档中。例如:
1908 
1909               BsonDocument order = new BsonDocument();
1910 
1911               BsonDocument items; // passed in from somewhere
1912 
1913               order.Add(items); // 元素现在在这两份文件
1914 
1915  
1916 
1917 或者,如果你不想共享的元素,这两个文件之间使用之一:
1918 
1919               order.Add((BsonDocument) items.Clone
1920 
1921               order.Add((BsonDocument) items.DeepClone());
1922 
1923  
1924 
1925 这取决于你是否需要浅或深的克隆。
1926 
1927 默认的行为是不能克隆,因为克隆是昂贵的,这样一来,我们默认情况下,最有效的行为,你会得到来决定何时克隆的成本是必要的。
1928 
1929 (IDictionary的<string,的对象)的方法
1930 这种方法增加了新的元素到基于一个BsonDocument的一本字典的内容。在字典中的每个键成为新元素的名称,以及每个对应的值成为新的元件的值。与往常一样,这个方法调用每个新元素的添加(BsonElement)的处理,所以重复的名称所描述的添加(BsonElement)。
1931 
1932 清除方法
1933 该方法将删除所有文档中的元素。
1934 
1935 Contains方法
1936 这种方法测试该文件是否包含给定名称的元素。
1937 
1938 ContainsValue方法
1939 此方法测试该文件是否包含与给定的值的元素。
1940 
1941 GetElement方法
1942 通常情况下,你会使用GetValue,或更常见相应的索引。在极少数情况下,您可能需要得到BsonElements自己使用的两种重载GetElement(如果指数,如果按名称)。
1943 
1944 GetValue方法和索引
1945 GetValue方法主要有三种形式:第一个数字索引,第二个需要的元素的名称,和第三也需要 一个默认值被返回,如果不存在该名称的元素。在所有情况下返回值类型BsonValue,。还设有一个匹配索引器每个GetValue方法。例如:
1946 
1947               BsonDocument book = books.FindOne();
1948 
1949               string author = book.GetValue(“author”).AsString;
1950 
1951               DateTime publicationDate =
1952 
1953 book.GetValue(“publicationDate”).AsDateTime;
1954 
1955               int pages = book.GetValue(“pages”).AsInt32;
1956 
1957               int pages = book.GetValue(“pages”, -1).AsInt32; / /默认-1
1958 
1959  
1960 
1961 或使用的索引,这是推荐的方法:
1962 
1963               BsonDocument book = books.FindOne();
1964 
1965               string author = book[“author”].AsString;
1966 
1967               DateTime publicationDate = book[“publicationDate”].AsDateTime;
1968 
1969               int pages = book[“pages”].AsInt32;
1970 
1971               int pages = book[“pages”, -1].AsInt32; / /默认-1
1972 
1973  
1974 
1975 由于BsonValue还支持显式转换到对应的。NET类型,这个例子也可以写成:
1976 
1977               BsonDocument book = books.FindOne();
1978 
1979               string author = (string) book[“author”];
1980 
1981               DateTime publicationDate = (DateTime) book[“publicationDate”];
1982 
1983               int pages = (int) book[“pages”];
1984 
1985               int pages = (int) book[“pages”, -1]; // default -1
1986 
1987  
1988 
1989 使用 这些方法, 你是一个个人选择的问题。我们建议第二种 方法(使用索引和[类型]属性),因为我们认为它是最可读的(不需要额外的括号有时需要的类型转换(可以是特别混乱时,他们被嵌套(它们经常是)))。比较下面的两个语句:
1990 
1991               / /每人是一个BsonDocument的了
1992 
1993               BsonDocument firstBorn =
1994 
1995 person[“children”].AsBsonArray [0]。AsDocument;
1996 
1997 BsonDocument firstBorn =
1998 
1999 (BsonDocument) ((BsonArray) person[“children”])[0];
2000 
2001  
2002 
2003 第一 是有点更容易读取从左到右。相同的事件序列是在这两种情况下发生:
2004 
2005 1.       被检索的个人文档的“孩子们”的元素(BsonValue)
2006 
2007 2. 该BsonValue转换为一个BsonArray
2008 
2009 3被检索的孩子数组的第一个元素(BsonValue)
2010 
2011 4:BsonValue转换为一个BsonDocument的
2012 
2013 有一个名字参数获取方法抛出一个异常,如果没有找到具有该名称的元素,并没有提供默认值 。请参阅TryGetValue方法,如果你不想要一个例外。
2014 
2015 Merge方法
2016 这种方法允许你合并元素从一个BsonDocument到另一个。从源文档的每个元件进行测试,以查看是否具有该名称的目标文档已经有一个元素。如果该名称已经存在,该元素将被跳过,如果不是,它被添加到目标文档。
2017 
2018 删除方法
2019 此方法用于删除一个元素从BsonDocument。如果允许重复的文件名,然后调用删除将删除与该名称的所有元素。
2020 
2021 RemoveAt方法
2022 此方法用于删除一个元素从一个BsonDocument使用它的索引位置。
2023 
2024 设置方法(指数值)
2025 虽然大多数的时候,你会访问元素的名称,偶尔会访问他们的指数。使用此方法时,该文件必须已经有一个元素在该指数或将抛出一个异常。有一个等价的索引。例如:
2026 
2027               book.Set(0, “Ernest Hemingway”); // assume element 0 is author
2028 
2029               book[0] = “Ernest Hemingway”; // shorter and better
2030 
2031 SET(名称,值)的方法
2032 如果这个名字的元素存在,它的值将被替换为新的值,否则这个名字和值的一个新的元素。例如:
2033 
2034               BsonDocument book = new BsonDocument();
2035 
2036               book.Set(“author”, “Ernest Hemway”); // adds element
2037 
2038               / /一些其他的工作
2039 
2040               / /注意,作者姓名拼写错误
2041 
2042 书的声音Set(“author”, “Ernest Hemingway”); // replaces value
2043 
2044  
2045 
2046 使用的索引器,前面的例子可以写成:
2047 
2048               BsonDocument book = new BsonDocument();
2049 
2050               book[“author”] = “Ernest Hemway”; // adds element
2051 
2052               / /一些其他的工作
2053 
2054               / /注意,作者姓名拼写错误
2055 
2056               book[“author”] = “Ernest Hemingway”; // replaces value
2057 
2058 ToBson方法
2059 此方法将BSON格式的二进制序列化的BsonDocument作为一个字节数组,并返回序列化的文件。
2060 
2061 toJSON方法
2062 此方法将序列化的BsonDocument的的一个JSON格式的字符串。这是可能的,有一定的控制生成的JSON表示提供一些BsonJsonWriterSettings的。
2063 
2064 ToString方法
2065 这种方法是覆盖调用的ToJSON使用默认设置。它主要用于调试。如果您有意创建JSON调用的ToJSON。
2066 
2067 TryGetElement和TryGetValue方法
2068 如果你不知道该文件所包含的元素与给定的名称,你可以第一个测试使用Contains方法或使用的TryGetElement或TryGetValue方法。例如:
2069 
2070               BsonValue age;
2071 
2072               if (person.TryGetValue(“age”, out age)) {
2073 
2074                             / /做一些事情随着年龄的增长
2075 
2076               } else {
2077 
2078                             / /处理丢失的年龄情况
2079 
2080               }
2081 
2082 BsonArray类
2083 这个类是用来代表BSON阵列。需要注意的是,而BSON阵列外部表示作为一个的BSON文档中(用一个特殊的命名约定的元素),C# 驱动程序 的BsonArray类是没有关系的的BsonDocument类。这是因为一个BsonArray作为BsonDocument外部表示的事实是偶然的,实际行为一个BsonArray是非常从一个BsonDocument不同。
2084 
2085 BsonArray构造函数
2086 您可以使用不带参数的构造函数创建一个空的数组,并同时将项目添加到数组,你可以使用C#的集合初始化器的语法:
2087 
2088               BsonArray a1 = new BsonArray(); // empty
2089 
2090               BsonArray a2 = new BsonArray { 1 }; // 1 element
2091 
2092               BsonArray a3 = new BsonArray { 1, 2, 3 }; // 3 elements
2093 
2094  
2095 
2096 还有一个构造函数的的IEnumerable的<BsonValue>参数(它调用 匹配 的 AddRange方法)。例如:
2097 
2098               IEnumerable<BsonValue> values; // from somewhere
2099 
2100               BsonArray a = new BsonArray(values); // adds values to array
2101 
2102  
2103 
2104 许多额外超载(IEnumerable的<int>的像)提供支持常见的情况,如:
2105 
2106               int[] values = new int[] { 1, 2, 3 };
2107 
2108               BsonArray a = new BsonArray(values);
2109 
2110  
2111 
2112 这个例子将不能正确编译的,因为IEnumerable <int>的不能自动转换到IEnumerable <BsonValue>的IEnumerable的<int>的过载。 IEnumerable的重载为布尔型,日期时间型,双,整型,长,对象和字符串。
2113 
2114 索引器属性
2115 这个类提供了一个索引属性来获取或设置数组中的元素。的索引器返回类型是 BsonValue,的,所以通常有做一些转换 。例如:
2116 
2117               array[0] = “Tom”;
2118 
2119               array[1] = 39;
2120 
2121               string name = array[0].AsString;
2122 
2123               int age = array[1].AsInt32;
2124 
2125 Count属性
2126 这个属性返回的值存储在BsonArray
2127 
2128 添加方法
2129 只有一个Add方法,它 一个BsonValue添加到数组(但也看到AddRange方法)。例如:
2130 
2131               BsonValue value; // from somewhere
2132 
2133               array.Add(value);
2134 
2135               array.Add(1); // implicit conversion from int to BsonInt32
2136 
2137 AddRange方法
2138 一个重载,AddRange方法需要的IEnumerable <BsonValue>参数和添加 多个项目的数组。例如:
2139 
2140               IEnumerable<BsonValue> values; // from somewhere
2141 
2142               array.AddRange(values); // adds values to array
2143 
2144  
2145 
2146 许多额外超载(IEnumerable的<int>的像)提供支持常见的情况,如:
2147 
2148               int[] values = new int[] { 1, 2, 3 };
2149 
2150               array.AddRange(values);
2151 
2152  
2153 
2154 这个例子将无法编译,因为IEnumerable <int>的不能被自动转换IEnumerable的 <BsonValue>的 没有了IEnumerable <int>的过载 。IEnumerable的重载为布尔型,日期时间型,双,整型,长,对象和字符串。
2155 
2156 清除方法
2157 此方法清除所有值的数组。
2158 
2159 的indexOf方法
2160 可以使用下面的indexOf方法找到在数组中的值的索引:
2161 
2162               int IndexOf(BsonValue value)
2163 
2164               int IndexOf(BsonValue value, int index)
2165 
2166               int IndexOf(BsonValue value, int index, int count)
2167 
2168  
2169 
2170 他们所有的工作一样名单<T>匹配的indexOf方法,则返回-1,如果没有匹配的数组中的项目。
2171 
2172 插入方法
2173 此方法用于添加一个值,在阵列中的一个特定的位置。例如:
2174 
2175               array.Insert(2, value);
2176 
2177  
2178 
2179 这个例子假设数组包含至少2个元素。如果包含两个以上的元素,索引2处的元素开始被移到一个位置,以腾出空间给新的元素。
2180 
2181 删除方法
2182 Remove方法从数组中删除一个特定的值。如果该值出现不止一次 在数组中,只有第一个实例被 删除。所有剩余的元素被转移到右侧,以便不留间隙,在阵列中,得到的数组会更短(除非没有匹配的元素被发现在这种情况下,这个方法没有任何效果)。
2183 
2184 RemoveAt方法
2185 此方法将删除从一个特定的值在数组中的位置。跟随它的任何元素移动一个位置向左侧和阵列是现在缩短一个元件的。
2186 
2187  
MongoDB的C#驱动程序教程(译)http://www.cnblogs.com/WilliamWang/archive/2012/10/19/MongoDB.html
   1 using MongoDB.Bson;
   2 using MongoDB.Driver;
   3 using MongoDB.Driver.Builders;
   4 using System;
   5 using System.Collections.Generic;
   6 using System.Linq;
   7 using System.Text;
   8 using System.Threading.Tasks;
   9 using NHibernate.Criterion;
  10 using NHibernate.Linq;
  11 using Spring.Transaction;
  12 using TX.Common.Domain;
  13 
  14 namespace TX.Common.Util
  15 {
  16     /// <summary>
  17     /// MongoDB相关操作类
  18     /// </summary>
  19     public static class MongoDBUtility
  20     {
  21         #region 属性
  22 
  23         private static string Ticket4DCollection = "Tx4DTicketPending";
  24         private static string Ticket6DCollection = "Tx6DTicketPending";
  25         private static string TicketPokerCollection = "TxPokerTicketPending";
  26         private static string TicketHorseCollection = "TxHorseTicketPending";
  27 
  28         private static string RunnerDetailCollection = "RunnerDetail";
  29         private static string HorseRunnersCollection = "HorseRunners";
  30 
  31         private static string PushCollection = "PushMarket";
  32 
  33         private static string strconn = System.Configuration.ConfigurationManager.AppSettings["mongoConn"];
  34         private static string dbName = System.Configuration.ConfigurationManager.AppSettings["mongoDB"];
  35 
  36         #endregion
  37 
  38         /// <summary>
  39         /// 获取collection对象
  40         /// </summary>
  41         /// <param name="collectionName"></param>
  42         /// <returns></returns>
  43         public static MongoCollection GetCollection(string collectionName)
  44         {
  45             if (!string.IsNullOrEmpty(collectionName))
  46             {
  47                 //创建数据库链接
  48                 MongoServer server = MongoServer.Create(strconn);
  49                 //获得数据库
  50                 //MongoClientSettings s = new MongoClientSettings();
  51                 //s.MinConnectionPoolSize = 10;
  52                 MongoDatabase db = server.GetDatabase(dbName);
  53 
  54                 MongoCollection col = db.GetCollection(collectionName);
  55                 return col;
  56             }
  57             return null;
  58         }
  59         
  60 
  61         #region 4D相关
  62 
  63         /*
  64         public static void Insert4D(Tx4DTicketPending user)
  65         {
  66             MongoCollection col = GetCollection(Ticket4DCollection);
  67             QueryDocument query = new QueryDocument { { "AcctId", user.AcctId } };
  68 
  69             long count = col.FindAs<Tx4DTicketPending>(query).Count();
  70             if (count < 1)
  71             {
  72                 WriteConcernResult result = col.Insert<Tx4DTicketPending>(user);
  73             }
  74         }
  75         */
  76 
  77         /// <summary>
  78         /// 获取所有in-play和matched的4D数据
  79         /// </summary>
  80         /// <returns></returns>
  81         public static IList<Tx4DTicketPending> Get4DAllDatas()
  82         {
  83             IList<Tx4DTicketPending> list=new List<Tx4DTicketPending>();
  84             IMongoQuery query = Query.Or(Query.EQ("Status", TicketStatus.PlayNow), Query.EQ("Status", TicketStatus.Matched));
  85             MongoCollection col = MongoDBUtility.GetCollection(Ticket4DCollection);
  86             if (col == null) return null;
  87             MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query);
  88             if (m != null && m.Count() > 0)
  89             {
  90                 foreach (var item in m)
  91                 {
  92                     list.Add(item);
  93                 }
  94             }
  95             return list;
  96         }
  97 
  98         public static bool Insert4DPending(Tx4DTicketPending pending)
  99         {
 100             if (pending != null)
 101             {
 102                 if (string.IsNullOrWhiteSpace(pending.PendingId))
 103                 {
 104                     pending._id = ObjectId.GenerateNewId();
 105                     pending.PendingId = pending._id.ToString();
 106                 }
 107                 MongoCollection col = GetCollection(Ticket4DCollection);
 108                 if (col != null)
 109                 {
 110                     WriteConcernResult result = col.Insert<Tx4DTicketPending>(pending);
 111                     return true;
 112                 }  
 113             }
 114             return false;
 115         }
 116         /// <summary>
 117         /// 获取最优的前三个4D的livenumber
 118         /// </summary>
 119         /// <param name="drawDateId"></param>
 120         /// <param name="marketName"></param>
 121         /// <param name="latters"></param>
 122         /// <param name="prizes"></param>
 123         /// <returns></returns>
 124         public static IList<LiveNumberInfo> GetTop3Live(int drawDateId, string marketName, List<string> latters, List<int> prizes)
 125         {
 126             IList<LiveNumberInfo> list = new List<LiveNumberInfo>();
 127             if (latters == null || latters.Count < 1) return list;
 128 
 129             //draw_date_id='" + drawDateId + "' and trim(bet_latter)
 130             List<IMongoQuery> sql = new List<IMongoQuery>();
 131 
 132             sql.Add(Query.EQ("DrawDateId", drawDateId));
 133             sql.Add(Query.EQ("Status", 0));
 134             
 135             IMongoQuery[] orlist=new IMongoQuery[latters.Count];
 136             for(int i=0;i<latters.Count;i++)
 137             {
 138                 orlist[i]=Query.EQ("BetLatter",latters[i]);
 139             }
 140             //sql.Add(Query.Or(orlist));
 141 
 142             IMongoQuery query = null;
 143             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 144 
 145             MongoCollection col = MongoDBUtility.GetCollection(Ticket4DCollection);
 146             if (col == null) return null;
 147 
 148             MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query);
 149             List<Tx4DTicketPending> data = new List<Tx4DTicketPending>();
 150             if (m != null && m.Count() > 0)
 151             {
 152                 foreach (var item in m)
 153                 {
 154                     data.Add(item);
 155                 }
 156             }
 157             list = GetTop3LiveFromIList(data, marketName, latters, prizes,null);
 158             return list;
 159         }
 160 
 161         public static IList<LiveNumberInfo> GetTop3Live(int drawDateId, string marketName, List<string> latters, List<int> prizes,IDictionary<string,int> latterAndNumbers)
 162         {
 163             IList<LiveNumberInfo> list = new List<LiveNumberInfo>();
 164             if (latters == null || latters.Count < 1) return list;
 165 
 166             //draw_date_id='" + drawDateId + "' and trim(bet_latter)
 167             List<IMongoQuery> sql = new List<IMongoQuery>();
 168 
 169             sql.Add(Query.EQ("DrawDateId", drawDateId));
 170             sql.Add(Query.EQ("Status", 0));
 171             
 172             IMongoQuery[] orlist = new IMongoQuery[latters.Count];
 173             for (int i = 0; i < latters.Count; i++)
 174             {
 175                 orlist[i] = Query.EQ("BetLatter", latters[i]);
 176             }
 177             //sql.Add(Query.Or(orlist));
 178 
 179             IMongoQuery query = null;
 180             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 181 
 182             MongoCollection col = MongoDBUtility.GetCollection(Ticket4DCollection);
 183             if (col == null) return null;
 184 
 185             MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query);
 186             List<Tx4DTicketPending> data = new List<Tx4DTicketPending>();
 187             if (m != null && m.Count() > 0)
 188             {
 189                 foreach (var item in m)
 190                 {
 191                     data.Add(item);
 192                 }
 193             }
 194             list = GetTop3LiveFromIList(data, marketName, latters, prizes, latterAndNumbers);
 195             return list;
 196         }
 197 
 198         /// <summary>
 199         /// 获取最优的前三个bsoe赔率
 200         /// </summary>
 201         /// <param name="drawDateId"></param>
 202         /// <param name="lotteryTime"></param>
 203         /// <param name="marketName"></param>
 204         /// <param name="ticketType"></param>
 205         /// <returns></returns>
 206         public static IList<BsoeInfo> GetTop3Bsoe(int drawDateId, DateTime lotteryTime,string marketName,IList<string> ticketType )
 207         {
 208             if (ticketType == null || ticketType.Count == 0)
 209             {
 210                 ticketType = new List<string>() {D4Type.Big, D4Type.Small, D4Type.Odd, D4Type.Even};
 211             }
 212 
 213             IList<BsoeInfo> list = new List<BsoeInfo>();
 214 
 215             List<IMongoQuery> sql = new List<IMongoQuery>();
 216 
 217             sql.Add(Query.EQ("DrawDateId", drawDateId));
 218             sql.Add(Query.EQ("Status", 0));
 219             if (lotteryTime <= DateTime.Now)
 220             {
 221                 sql.Add(Query.Or(Query.EQ("AllInPlay",1),Query.GT("CreateTime",lotteryTime)));
 222             }
 223 
 224             IMongoQuery[] orlist = new IMongoQuery[ticketType.Count];
 225             for (int i = 0; i < ticketType.Count; i++)
 226             {
 227                 orlist[i] = Query.EQ("TicketType", ticketType[i]);
 228             }
 229             sql.Add(Query.Or(orlist));
 230 
 231             IMongoQuery query = null;
 232             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 233 
 234             MongoCollection col = MongoDBUtility.GetCollection(Ticket4DCollection);
 235             if (col == null) return null;
 236 
 237             MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query);
 238             List<Tx4DTicketPending> data = new List<Tx4DTicketPending>();
 239             if (m != null && m.Count() > 0)
 240             {
 241                 foreach (var item in m)
 242                 {
 243                     data.Add(item);
 244                 }
 245             }
 246 
 247             list = GetTop3BsoeFromIList(data, lotteryTime, marketName, ticketType);
 248             return list;
 249         }
 250 
 251         /// <summary>
 252         /// 当开奖时间到了,将标记为canncel的ticket的状态设置为取消
 253         /// </summary>
 254         /// <param name="drawDateId"></param>
 255         /// <param name="lotteryTime"></param>
 256         /// <returns></returns>
 257         public static bool UpdateCancelTicketExpired(int drawDateId, DateTime lotteryTime)
 258         {
 259             IList<string> ticketType = new List<string>() { D4Type.Big, D4Type.Small, D4Type.Odd, D4Type.Even };
 260             List<IMongoQuery> sql = new List<IMongoQuery>();
 261 
 262             sql.Add(Query.EQ("DrawDateId", drawDateId));
 263             sql.Add(Query.EQ("Status", 0));
 264             
 265 
 266             //下注时间在开奖前,同时设置的是cancel,而非keep
 267             sql.Add(Query.LT("CreateTime",lotteryTime));
 268             sql.Add(Query.EQ("AllInPlay", 0));
 269 
 270             IMongoQuery[] orlist = new IMongoQuery[ticketType.Count];
 271             for (int i = 0; i < ticketType.Count; i++)
 272             {
 273                 orlist[i] = Query.EQ("TicketType", ticketType[i]);
 274             }
 275             sql.Add(Query.Or(orlist));
 276 
 277             IMongoQuery query = null;
 278             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 279 
 280             IMongoUpdate update = Update.Set("Status", TicketStatus.Canceled);
 281 
 282             MongoCollection col = MongoDBUtility.GetCollection(Ticket4DCollection);
 283             if (col == null) return false;
 284 
 285             col.Update(query, update);
 286             return true;
 287         }
 288 
 289         /// <summary>
 290         /// 获取所有已经过期了的cancel标记的ticket
 291         /// </summary>
 292         /// <param name="drawDateId"></param>
 293         /// <param name="lotteryTime"></param>
 294         /// <returns></returns>
 295         public static IList<Tx4DTicketPending> GetAllExpiredCancelTicket4D(int drawDateId, DateTime lotteryTime)
 296         {
 297             IList<string> ticketType = new List<string>() { D4Type.Big, D4Type.Small, D4Type.Odd, D4Type.Even };
 298             List<IMongoQuery> sql = new List<IMongoQuery>();
 299 
 300             sql.Add(Query.EQ("DrawDateId", drawDateId));
 301             sql.Add(Query.EQ("Status", 0));
 302             sql.Add(Query.NE("AcctId","system"));
 303             //下注时间在开奖前,同时设置的是cancel,而非keep
 304             sql.Add(Query.LT("CreateTime", lotteryTime));
 305             sql.Add(Query.EQ("AllInPlay", 0));
 306 
 307             IMongoQuery[] orlist = new IMongoQuery[ticketType.Count];
 308             for (int i = 0; i < ticketType.Count; i++)
 309             {
 310                 orlist[i] = Query.EQ("TicketType", ticketType[i]);
 311             }
 312             sql.Add(Query.Or(orlist));
 313 
 314             IMongoQuery query = null;
 315             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 316 
 317             IMongoUpdate update = Update.Set("Status", TicketStatus.Canceled);
 318 
 319             MongoCollection col = MongoDBUtility.GetCollection(Ticket4DCollection);
 320             if (col == null) return null;
 321 
 322             MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query);
 323             List<Tx4DTicketPending> data = new List<Tx4DTicketPending>();
 324             if (m != null && m.Count() > 0)
 325             {
 326                 foreach (var item in m)
 327                 {
 328                     data.Add(item);
 329                 }
 330             }
 331             return data;
 332         }
 333 
 334         /// <summary>
 335         /// 获取所有已经过期了的cancel标记的ticket
 336         /// </summary>
 337         /// <param name="drawDateId"></param>
 338         /// <param name="lotteryTime"></param>
 339         /// <returns></returns>
 340         public static IList<Tx6DTicketPending> GetAllExpiredCancelTicket6D(int drawDateId, DateTime lotteryTime)
 341         {
 342             IList<string> ticketType = new List<string>() { D6Type.High, D6Type.Low,D6Type.ExtraBet,D6Type.ExtraEat };
 343             List<IMongoQuery> sql = new List<IMongoQuery>();
 344 
 345             sql.Add(Query.EQ("Status", 0));
 346             sql.Add(Query.EQ("DrawDateId", drawDateId));
 347             sql.Add(Query.NE("AcctId", "system"));
 348             //下注时间在开奖前,同时设置的是cancel,而非keep
 349             sql.Add(Query.LT("CreateTime", lotteryTime));
 350             sql.Add(Query.EQ("AllInPlay", 0));
 351 
 352             IMongoQuery[] orlist = new IMongoQuery[ticketType.Count];
 353             for (int i = 0; i < ticketType.Count; i++)
 354             {
 355                 orlist[i] = Query.EQ("TicketType", ticketType[i]);
 356             }
 357             sql.Add(Query.Or(orlist));
 358 
 359             IMongoQuery query = null;
 360             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 361 
 362             IMongoUpdate update = Update.Set("Status", TicketStatus.Canceled);
 363 
 364             MongoCollection col = MongoDBUtility.GetCollection(Ticket6DCollection);
 365             if (col == null) return null;
 366 
 367             MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query);
 368             List<Tx6DTicketPending> data = new List<Tx6DTicketPending>();
 369             if (m != null && m.Count() > 0)
 370             {
 371                 foreach (var item in m)
 372                 {
 373                     data.Add(item);
 374                 }
 375             }
 376             return data;
 377         }
 378 
 379         /// <summary>
 380         /// 根据pendingId获取对象
 381         /// </summary>
 382         /// <param name="pendingId"></param>
 383         /// <returns></returns>
 384         public static Tx4DTicketPending GetOne4D(string pendingId)
 385         {
 386             IMongoQuery query = Query.EQ("_id", ObjectId.Parse(pendingId));
 387             MongoCollection col = GetCollection(Ticket4DCollection);
 388             if (col != null)
 389             {
 390                 var result = col.FindOneAs<Tx4DTicketPending>(query);
 391                 return result;
 392             }
 393             return null;
 394         }
 395 
 396         public static bool Update4D(IMongoQuery query,IMongoUpdate update)
 397         {
 398             MongoCollection col = GetCollection(Ticket4DCollection);
 399             if (col != null)
 400             {
 401                 col.Update(query, update);
 402                 return true;
 403             }
 404             /*
 405             long count = col.FindAs<Tx4DTicketPending>(query).Count();
 406             if (count > 0)
 407             {
 408                 //var update = new UpdateDocument { { "$set", new QueryDocument { { "img", img } } } };
 409                 //执行更新操作
 410                 col.Update(query, update);
 411 
 412                 //var u = Update.Set("Title", "yanc").Set();
 413                 return true;
 414             }
 415             */
 416             return false;
 417         }
 418 
 419         public static bool Detele4D(IMongoQuery query)
 420         {
 421             MongoCollection col = GetCollection(Ticket4DCollection);
 422             if (col != null)
 423             {
 424                 WriteConcernResult result = col.Remove(query);
 425                 return true;
 426             }
 427             return false;
 428         }
 429 
 430         public static bool Update4DList(IMongoQuery query, IMongoUpdate update)
 431         {
 432             MongoCollection col = GetCollection(Ticket4DCollection);
 433             if (col != null)
 434             {
 435                 col.Update(query, update, UpdateFlags.Multi);
 436                 return true;
 437             }
 438 
 439             /*
 440             long count = col.FindAs<Tx4DTicketPending>(query).Count();
 441             if (count > 0)
 442             {
 443                 //var update = new UpdateDocument { { "$set", new QueryDocument { { "img", img } } } };
 444                 //执行更新操作
 445                 col.Update(query, update,UpdateFlags.Multi);
 446                 //var u = Update.Set("Title", "yanc").Set();
 447                 return true;
 448             }
 449             */
 450             return false;
 451         }
 452 
 453         public static IList<Tx4DTicketPending> GetListByQuery(IMongoQuery query)
 454         {
 455             if (query != null)
 456             {
 457                 MongoCollection col = GetCollection(Ticket4DCollection);
 458                 if (col == null) return null;
 459                 MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query);
 460                 List<Tx4DTicketPending> data = new List<Tx4DTicketPending>();
 461                 if (m != null && m.Count() > 0)
 462                 {
 463                     foreach (var item in m)
 464                     {
 465                         data.Add(item);
 466                     }
 467                 }
 468                 return data;
 469             }
 470             return null;
 471         }
 472 
 473         public static IList<Tx4DTicketPending> GetListByQuery(IMongoQuery query,IMongoSortBy s)
 474         {
 475             if (query != null)
 476             {
 477                 MongoCollection col = GetCollection(Ticket4DCollection);
 478                 if (col == null) return null;
 479                 MongoCursor<Tx4DTicketPending> m = col.FindAs<Tx4DTicketPending>(query).SetSortOrder(s);
 480                 List<Tx4DTicketPending> data = new List<Tx4DTicketPending>();
 481                 if (m != null && m.Count() > 0)
 482                 {
 483                     foreach (var item in m)
 484                     {
 485                         data.Add(item);
 486                     }
 487                 }
 488                 return data;
 489             }
 490             return null;
 491         }
 492 
 493         #endregion
 494 
 495 
 496         #region 6D相关
 497 
 498         /// <summary>
 499         /// 获取所有in-play和matched的4D数据
 500         /// </summary>
 501         /// <returns></returns>
 502         public static IList<Tx6DTicketPending> Get6DAllDatas()
 503         {
 504             IList<Tx6DTicketPending> list = new List<Tx6DTicketPending>();
 505             IMongoQuery query = Query.Or(Query.EQ("Status", TicketStatus.PlayNow), Query.EQ("Status", TicketStatus.Matched));
 506             MongoCollection col = MongoDBUtility.GetCollection(Ticket6DCollection);
 507             if (col == null) return null;
 508             MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query);
 509             if (m != null && m.Count() > 0)
 510             {
 511                 foreach (var item in m)
 512                 {
 513                     list.Add(item);
 514                 }
 515             }
 516             return list;
 517         }
 518 
 519         public static bool Insert6DPending(Tx6DTicketPending pending)
 520         {
 521             if (pending != null)
 522             {
 523                 if (string.IsNullOrWhiteSpace(pending.PendingId))
 524                 {
 525                     pending._id = ObjectId.GenerateNewId();
 526                     pending.PendingId = pending._id.ToString();
 527                 }
 528                 MongoCollection col = GetCollection(Ticket6DCollection);
 529                 if (col != null)
 530                 {
 531                     WriteConcernResult result = col.Insert<Tx6DTicketPending>(pending);
 532                     return true;
 533                 } 
 534             }
 535             return false;
 536         }
 537 
 538         public static bool Insert6DPendingList(IList<Tx6DTicketPending> list)
 539         {
 540             if (list != null && list.Count>0)
 541             {
 542                 MongoCollection col = GetCollection(Ticket6DCollection);
 543                 if (col != null)
 544                 {
 545                     var result = col.InsertBatch<Tx6DTicketPending>(list);
 546                     return true;
 547                 }
 548             }
 549             return false;
 550         }
 551 
 552         public static IList<LiveNumberInfo> Get6DTop3Live(int drawDateId, string marketName, string[] numbers)
 553         {
 554             IList<LiveNumberInfo> list = new List<LiveNumberInfo>();
 555             if (numbers == null || numbers.Length < 1) return list;
 556 
 557             //draw_date_id='" + drawDateId + "' and trim(bet_latter)
 558             List<IMongoQuery> sql = new List<IMongoQuery>();
 559 
 560             sql.Add(Query.EQ("Status", 0));
 561             sql.Add(Query.EQ("DrawDateId", drawDateId));
 562             IMongoQuery[] orlist = new IMongoQuery[numbers.Length];
 563             for (int i = 0; i < numbers.Length; i++)
 564             {
 565                 orlist[i] = Query.EQ("BetNumber", numbers[i]);
 566             }
 567             //sql.Add(Query.Or(orlist));
 568 
 569             IMongoQuery query = null;
 570             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 571 
 572             MongoCollection col = MongoDBUtility.GetCollection(Ticket6DCollection);
 573             if (col == null) return null;
 574             MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query);
 575             List<Tx6DTicketPending> data = new List<Tx6DTicketPending>();
 576             if (m != null && m.Count() > 0)
 577             {
 578                 foreach (var item in m)
 579                 {
 580                     data.Add(item);
 581                 }
 582             }
 583             list = Get6DTop3LiveFromIList(data, marketName, numbers);
 584             return list;
 585         }
 586 
 587         public static IList<HiLoInfo> GetTop3Hilo(GameDrawDate drawDate)
 588         {
 589             /*
 590             string timeWhere = "";
 591             if (drawDate.Lotterytime <= DateTime.Now)
 592             {
 593                 timeWhere = " and (all_in_play='1' or (create_time>draw_date))";
 594             }
 595             string sql = "select odds_euro,sum(num_euro) as num,ticket_type from (select * from ticket_6d_pending where status='0' and draw_date_id='" + drawDate.Id + "'" + timeWhere + ") as t group by odds_euro,ticket_type having ";
 596 
 597             string hiSql = "select * from (" + sql + "ticket_type='" + D6Type.Low + "' order by odds_euro desc limit 3) as bet";
 598             string loSql = "select * from (" + sql + "ticket_type='" + D6Type.High + "' order by odds_euro desc limit 3) as eat";
 599             string exeSql = hiSql + " union " + loSql;
 600             DataSet ds = SqliteHelper.Instance.GetData(exeSql, CommandType.Text);
 601             IList<HiLoInfo> list = ConvertHiLoList2(ds, drawDate.SysMarket.Name);
 602             */
 603 
 604             var list = new List<HiLoInfo>();
 605             List<IMongoQuery> sql = new List<IMongoQuery>();
 606             sql.Add(Query.EQ("Status", 0));
 607             sql.Add(Query.EQ("DrawDateId", drawDate.Id));
 608             if (drawDate.Lotterytime <= DateTime.Now)
 609             {
 610                 sql.Add(Query.Or(Query.EQ("AllInPlay", 1), Query.GT("CreateTime", drawDate.Lotterytime)));
 611             }
 612             sql.Add(Query.Or(Query.EQ("TicketType",D6Type.Low),Query.EQ("TicketType",D6Type.High)));
 613 
 614             IMongoQuery query = null;
 615             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 616 
 617             MongoCollection col = MongoDBUtility.GetCollection(Ticket6DCollection);
 618             if (col == null) return null;
 619 
 620             MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query);
 621             List<Tx6DTicketPending> data = new List<Tx6DTicketPending>();
 622             if (m != null && m.Count() > 0)
 623             {
 624                 foreach (var item in m)
 625                 {
 626                     data.Add(item);
 627                 }
 628             }
 629             return GetTop3HiloFromIList(data, drawDate);
 630         }
 631 
 632         public static IList<HiLoInfo> GetTop3HiloMaybeNew(GameDrawDate drawDate,int opened)
 633         {
 634             var list = new List<HiLoInfo>();
 635             List<IMongoQuery> sql = new List<IMongoQuery>();
 636             sql.Add(Query.EQ("Status", 0));
 637             sql.Add(Query.EQ("DrawDateId", drawDate.Id));
 638             if (drawDate.Lotterytime <= DateTime.Now)
 639             {
 640                 sql.Add(Query.Or(Query.EQ("AllInPlay", 1), Query.GT("CreateTime", drawDate.Lotterytime)));
 641             }
 642             sql.Add(Query.Or(Query.EQ("TicketType", D6Type.Low), Query.EQ("TicketType", D6Type.High)));
 643 
 644             IMongoQuery query = null;
 645             if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 646 
 647             MongoCollection col = MongoDBUtility.GetCollection(Ticket6DCollection);
 648             if (col == null) return null;
 649 
 650             MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query);
 651             List<Tx6DTicketPending> data = new List<Tx6DTicketPending>();
 652             if (m != null && m.Count() > 0)
 653             {
 654                 foreach (var item in m)
 655                 {
 656                     data.Add(item);
 657                 }
 658             }
 659             //--------------------------------
 660             if (data.Count == 0)//如果等于0,那么又两种情况,一种是该期刚创建,还没有生成hilo赔率,一种是本来生成了,但被全部matched,针对这两种情况,要做下判断,如果是第一种,则创建hilo赔率,如果是第二种,则不用理,直接返回“-”的数据则ok
 661             {
 662                 IMongoQuery tmp = Query.And(Query.EQ("DrawDateId", drawDate.Id), Query.EQ("TicketType", D6Type.Low));
 663                 m = col.FindAs<Tx6DTicketPending>(tmp);
 664                 if (m == null || (!m.Any()))//如果找不到任何数据,说明第一次访问!
 665                 {
 666                     m = col.FindAs<Tx6DTicketPending>(query);
 667                     if (m != null && m.Count()>0)
 668                     {
 669                         foreach (var item in m)
 670                         {
 671                             data.Add(item);
 672                         }
 673                     }
 674                 }
 675             }
 676             //-----------------------------------
 677             return GetTop3HiloFromIList(data, drawDate);
 678         }
 679 
 680         public static Tx6DTicketPending GetOne6D(string pendingId)
 681         {
 682             IMongoQuery query = Query.EQ("_id", ObjectId.Parse(pendingId));
 683             MongoCollection col = GetCollection(Ticket6DCollection);
 684             if (col != null)
 685             {
 686                 var result = col.FindOneAs<Tx6DTicketPending>(query);
 687                 return result;
 688             }
 689             return null;
 690         }
 691 
 692         public static bool Update6D(IMongoQuery query, IMongoUpdate update)
 693         {
 694             MongoCollection col = GetCollection(Ticket6DCollection);
 695             if (col != null)
 696             {
 697                 col.Update(query, update);
 698                 return true;
 699             }
 700             /*
 701             long count = col.FindAs<Tx6DTicketPending>(query).Count();
 702             if (count > 0)
 703             {
 704                 //var update = new UpdateDocument { { "$set", new QueryDocument { { "img", img } } } };
 705                 //执行更新操作
 706                 col.Update(query, update);
 707 
 708                 //var u = Update.Set("Title", "yanc").Set();
 709                 return true;
 710             }
 711             */
 712             return false;
 713         }
 714 
 715         public static bool Detele6D(IMongoQuery query)
 716         {
 717             MongoCollection col = GetCollection(Ticket6DCollection);
 718             if (col != null)
 719             {
 720                 WriteConcernResult result = col.Remove(query);
 721                 return true;
 722             }
 723             return false;
 724         }
 725 
 726         public static bool Update6DList(IMongoQuery query, IMongoUpdate update)
 727         {
 728             MongoCollection col = GetCollection(Ticket6DCollection);
 729             if (col != null)
 730             {
 731                 col.Update(query, update, UpdateFlags.Multi);
 732                 return true;
 733             }
 734             return false;
 735         }
 736 
 737         public static IList<Tx6DTicketPending> Get6DListByQuery(IMongoQuery query)
 738         {
 739             if (query != null)
 740             {
 741                 MongoCollection col = GetCollection(Ticket6DCollection);
 742                 if (col == null) return null;
 743 
 744                 MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query);
 745                 List<Tx6DTicketPending> data = new List<Tx6DTicketPending>();
 746                 if (m != null && m.Count() > 0)
 747                 {
 748                     foreach (var item in m)
 749                     {
 750                         data.Add(item);
 751                     }
 752                 }
 753                 return data;
 754             }
 755             return null;
 756         }
 757 
 758         public static IList<Tx6DTicketPending> Get6DListByQuery(IMongoQuery query, IMongoSortBy s)
 759         {
 760             if (query != null)
 761             {
 762                 MongoCollection col = GetCollection(Ticket6DCollection);
 763                 if (col == null) return null;
 764 
 765                 MongoCursor<Tx6DTicketPending> m = col.FindAs<Tx6DTicketPending>(query).SetSortOrder(s);
 766                 List<Tx6DTicketPending> data = new List<Tx6DTicketPending>();
 767                 if (m != null && m.Count() > 0)
 768                 {
 769                     foreach (var item in m)
 770                     {
 771                         data.Add(item);
 772                     }
 773                 }
 774                 return data;
 775             }
 776             return null;
 777         }
 778 
 779         #endregion
 780 
 781 
 782         #region Poker相关
 783 
 784         public static bool InsertPokerPending(TxPokerTicketPending pending)
 785           {
 786               if (pending != null)
 787               {
 788                   if (string.IsNullOrWhiteSpace(pending.PendingId))
 789                   {
 790                       pending._id = ObjectId.GenerateNewId();
 791                       pending.PendingId = pending._id.ToString();
 792                   }
 793                   MongoCollection col = GetCollection(TicketPokerCollection);
 794                   if (col != null)
 795                   {
 796                       WriteConcernResult result = col.Insert<TxPokerTicketPending>(pending);
 797                       return true;
 798                   }
 799               }
 800               return false;
 801           }
 802 
 803         public static IList<LiveNumberInfo> GetTop3Poker(int drawDateId, IList<int> hands)
 804           {
 805               var list = new List<LiveNumberInfo>();
 806               if (hands == null || hands.Count < 1) return list;
 807 
 808               List<IMongoQuery> sql = new List<IMongoQuery>();
 809 
 810               sql.Add(Query.EQ("Status", 0));
 811               sql.Add(Query.EQ("DrawDateId", drawDateId));
 812               IMongoQuery[] orlist = new IMongoQuery[hands.Count];
 813               for (int i = 0; i < hands.Count; i++)
 814               {
 815                   orlist[i] = Query.EQ("Hand", hands[i]);
 816               }
 817               //sql.Add(Query.Or(orlist));
 818 
 819               IMongoQuery query = null;
 820               if (sql.Count > 0) { query = Query.And(sql.ToArray()); }
 821 
 822               MongoCollection col = MongoDBUtility.GetCollection(TicketPokerCollection);
 823               if (col == null) return null;
 824               MongoCursor<TxPokerTicketPending> m = col.FindAs<TxPokerTicketPending>(query);
 825               List<TxPokerTicketPending> data = new List<TxPokerTicketPending>();
 826               if (m != null && m.Count() > 0)
 827               {
 828                   foreach (var item in m)
 829                   {
 830                       data.Add(item);
 831                   }
 832               }
 833 
 834               for (int i = 0; i < hands.Count; i++)
 835               {
 836                   string number = "0000";
 837                   //获取bet部分
 838                   IList<TxPokerTicketPending> a = data.Where(item => (item.Hand == hands[i] && item.TicketType == PokerType.Eat)).ToList();
 839                   var abet = (from it in a
 840                               group it by it.Odds into g
 841                               select new LiveNumberInfo()
 842                               {
 843                                   IsBet = true,
 844                                   Latter = hands[i].ToString(),
 845                                   Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
 846                                   Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumEuro; }).Value, 0)
 847                               }).OrderByDescending(item => item.Odds).Take(3).ToList();
 848 
 849                   abet = SetIndex(abet);
 850                   if (abet != null && abet.Count > 0) number = abet[0].Number;
 851                   abet = GameHelper.AddTempLiveNumber(abet, true, hands[i].ToString(), null, null, 0);
 852 
 853                   //获取eat部分
 854                   IList<TxPokerTicketPending> b = data.Where(item => (item.Hand == hands[i] && item.TicketType == PokerType.Bet)).ToList();
 855                   var bbet = (from it in b
 856                               group it by it.Odds into g
 857                               select new LiveNumberInfo()
 858                               {
 859                                   IsBet = false,
 860                                   Latter = hands[i].ToString(),
 861                                   Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
 862                                   Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumEuro; }).Value, 0)
 863                               }).OrderBy(item => item.Odds).Take(3).ToList();
 864 
 865                   bbet = SetIndex(bbet);
 866                   if (bbet != null && bbet.Count > 0) number = bbet[0].MarketName;
 867                   bbet = GameHelper.AddTempLiveNumber(bbet, false, hands[i].ToString(), null, null, 0);
 868 
 869                   list.AddRange(abet);
 870                   list.AddRange(bbet);
 871               }
 872               return list;
 873           }
 874 
 875         public static TxPokerTicketPending GetOnePoker(string pendingId)
 876           {
 877               IMongoQuery query = Query.EQ("_id", ObjectId.Parse(pendingId));
 878               MongoCollection col = GetCollection(TicketPokerCollection);
 879               if (col != null)
 880               {
 881                   var result = col.FindOneAs<TxPokerTicketPending>(query);
 882                   return result;
 883               }
 884               return null;
 885           }
 886 
 887         public static bool UpdatePoker(IMongoQuery query, IMongoUpdate update)
 888           {
 889               MongoCollection col = GetCollection(TicketPokerCollection);
 890               if (col != null)
 891               {
 892                   col.Update(query, update);
 893                   return true;
 894               }
 895               return false;
 896           }
 897 
 898         public static bool DetelePoker(IMongoQuery query)
 899           {
 900               MongoCollection col = GetCollection(TicketPokerCollection);
 901               if (col != null)
 902               {
 903                   WriteConcernResult result = col.Remove(query);
 904                   return true;
 905               }
 906               return false;
 907           }
 908 
 909         public static bool UpdatePokerList(IMongoQuery query, IMongoUpdate update)
 910           {
 911               MongoCollection col = GetCollection(TicketPokerCollection);
 912               if (col != null)
 913               {
 914                   col.Update(query, update, UpdateFlags.Multi);
 915                   return true;
 916               }
 917               return false;
 918           }
 919 
 920         public static IList<TxPokerTicketPending> GetPokerListByQuery(IMongoQuery query)
 921           {
 922               if (query != null)
 923               {
 924                   MongoCollection col = GetCollection(TicketPokerCollection);
 925                   if (col == null) return null;
 926 
 927                   MongoCursor<TxPokerTicketPending> m = col.FindAs<TxPokerTicketPending>(query);
 928                   List<TxPokerTicketPending> data = new List<TxPokerTicketPending>();
 929                   if (m != null && m.Count() > 0)
 930                   {
 931                       foreach (var item in m)
 932                       {
 933                           data.Add(item);
 934                       }
 935                   }
 936                   return data;
 937               }
 938               return null;
 939           }
 940 
 941         public static IList<TxPokerTicketPending> GetPokerListByQuery(IMongoQuery query, IMongoSortBy s)
 942           {
 943               if (query != null)
 944               {
 945                   MongoCollection col = GetCollection(TicketPokerCollection);
 946                   if (col == null) return null;
 947 
 948                   MongoCursor<TxPokerTicketPending> m = col.FindAs<TxPokerTicketPending>(query).SetSortOrder(s);
 949                   List<TxPokerTicketPending> data = new List<TxPokerTicketPending>();
 950                   if (m != null && m.Count() > 0)
 951                   {
 952                       foreach (var item in m)
 953                       {
 954                           data.Add(item);
 955                       }
 956                   }
 957                   return data;
 958               }
 959               return null;
 960           }
 961         
 962         #endregion
 963 
 964 
 965         #region horse相关
 966 
 967         public static bool InsertHorsePending(TxHorseTicketPending pending)
 968         {
 969             if (pending != null)
 970             {
 971                 if (string.IsNullOrWhiteSpace(pending.PendingId))
 972                 {
 973                     pending._id = ObjectId.GenerateNewId();
 974                     pending.PendingId = pending._id.ToString();
 975                 }
 976                 MongoCollection col = GetCollection(TicketHorseCollection);
 977                 if (col != null)
 978                 {
 979                     WriteConcernResult result = col.Insert<TxHorseTicketPending>(pending);
 980                     return true;
 981                 }
 982             }
 983             return false;
 984         }
 985 
 986         public static IList<TxHorseTicketPending> GetHorseListByQuery(IMongoQuery query)
 987         {
 988             if (query != null)
 989             {
 990                 MongoCollection col = GetCollection(TicketHorseCollection);
 991                 if (col == null) return null;
 992 
 993                 MongoCursor<TxHorseTicketPending> m = col.FindAs<TxHorseTicketPending>(query);
 994                 List<TxHorseTicketPending> data = new List<TxHorseTicketPending>();
 995                 if (m != null && m.Count() > 0)
 996                 {
 997                     data.AddRange(m);
 998                 }
 999                 return data;
1000             }
1001             return null;
1002         }
1003 
1004         public static IList<LiveNumberInfoByHorse> GetTop3Horse(string gameId, List<string> runnerIds)
1005         {
1006             var list = new List<LiveNumberInfoByHorse>();
1007             if (runnerIds == null || runnerIds.Count < 1) return list;
1008 
1009             var sql = new List<IMongoQuery> { Query.EQ("Status", 0), Query.EQ("MarketId", gameId) };
1010 
1011             //var orlist = new IMongoQuery[runnerIds.Count];
1012             //for (int i = 0; i < runnerIds.Count; i++)
1013             //{
1014             //    orlist[i] = Query.EQ("RunnerId", runnerIds[i]);
1015             //}
1016 
1017             IMongoQuery query = null;
1018             if (sql.Count > 0)
1019             {
1020                 query = Query.And(sql.ToArray());
1021             }
1022 
1023             MongoCollection col = MongoDBUtility.GetCollection(TicketHorseCollection);
1024             if (col == null) return null;
1025 
1026             MongoCursor<TxHorseTicketPending> m = col.FindAs<TxHorseTicketPending>(query);
1027             var data = new List<TxHorseTicketPending>();
1028 
1029 
1030             if (m != null && m.Count() > 0)
1031             {
1032                 data.AddRange(m);
1033             }
1034 
1035             foreach (string runner in runnerIds)
1036             {
1037                 //获取bet部分
1038                 IList<TxHorseTicketPending> a =
1039                     data.Where(
1040                         item => item.MarketId==gameId && item.RunnerId != null &&
1041                             (item.RunnerId.Value.ToString() == runner && item.TicketType == HorseType.Bet)).ToList();
1042                 var abet = (from it in a
1043                             group it by it.Odds
1044                                 into g
1045                                 select new LiveNumberInfoByHorse()
1046                                 {
1047                                     IsBet = true,
1048                                     RunId = runner,
1049                                     GameId = gameId,
1050                                     Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1051                                     Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1052                                 }).OrderByDescending(item => item.Odds).Take(3).ToList();
1053 
1054                 abet = SetIndex(abet);
1055                 abet = GameHelper.AddTempLiveNumber(abet, true, runner, gameId).ToList();
1056 
1057                 //获取eat部分
1058                 IList<TxHorseTicketPending> b =
1059                     data.Where(
1060                         item => item.MarketId==gameId && item.RunnerId != null &&
1061                             (item.RunnerId.Value.ToString() == runner && item.TicketType == HorseType.Eat)).ToList();
1062                 var bbet = (from it in b
1063                             group it by it.Odds
1064                                 into g
1065                                 select new LiveNumberInfoByHorse()
1066                                 {
1067                                     IsBet = false,
1068                                     RunId = runner,
1069                                     GameId = gameId,
1070                                     Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1071                                     Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1072                                 }).OrderBy(item => item.Odds).Take(3).ToList();
1073 
1074                 bbet = SetIndex(bbet);
1075                 bbet = GameHelper.AddTempLiveNumber(bbet, false, runner, gameId).ToList();
1076                 if (abet != null) list.AddRange(abet);
1077                 if (bbet != null) list.AddRange(bbet);
1078             }
1079             return list;
1080         }
1081 
1082         /// <summary>
1083         /// 通过runner id 集合获取top 3赔率数据
1084         /// </summary>
1085         /// <param name="runnerIds"></param>
1086         /// <returns></returns>
1087         public static IList<LiveNumberInfoByHorse> GetTop3Horse(IList<int> runnerIds)
1088         {
1089             if (runnerIds != null && runnerIds.Count > 0)
1090             {
1091                 var sql = new List<IMongoQuery> { Query.EQ("Status", 0), Query.In("RunnerId", new BsonArray(runnerIds)) };
1092 
1093                 IMongoQuery query = null;
1094                 if (sql.Count > 0)
1095                 {
1096                     query = Query.And(sql.ToArray());
1097                 }
1098 
1099                 MongoCollection col = MongoDBUtility.GetCollection(TicketHorseCollection);
1100                 if (col == null) return null;
1101 
1102                 MongoCursor<TxHorseTicketPending> m = col.FindAs<TxHorseTicketPending>(query);
1103                 var data = new List<TxHorseTicketPending>();
1104                 var list = new List<LiveNumberInfoByHorse>();
1105                 if (m != null && m.Count() > 0)
1106                 {
1107                     data.AddRange(m);
1108                 }
1109                 foreach (int runner in runnerIds)
1110                 {
1111                     //获取bet部分
1112                     IList<TxHorseTicketPending> a =
1113                         data.Where(
1114                             item =>
1115                                 item.RunnerId != null &&
1116                                 (item.RunnerId == runner && item.TicketType == HorseType.Bet)).ToList();
1117                     var abet = (from it in a
1118                                 group it by it.Odds
1119                                     into g
1120                                     select new LiveNumberInfoByHorse()
1121                                     {
1122                                         IsBet = true,
1123                                         RunId = runner.ToString(),
1124                                         Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1125                                         Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1126                                     }).OrderByDescending(item => item.Odds).Take(3).ToList();
1127 
1128                     abet = SetIndex(abet);
1129                     abet = GameHelper.AddTempLiveNumber(abet, true, runner.ToString(), null).ToList();
1130                     //获取eat部分
1131                     IList<TxHorseTicketPending> b =
1132                         data.Where(
1133                             item =>
1134                                 item.RunnerId != null &&
1135                                 (item.RunnerId == runner && item.TicketType == HorseType.Eat)).ToList();
1136                     var bbet = (from it in b
1137                                 group it by it.Odds
1138                                     into g
1139                                     select new LiveNumberInfoByHorse()
1140                                     {
1141                                         IsBet = false,
1142                                         RunId = runner.ToString(),
1143                                         Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1144                                         Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1145                                     }).OrderBy(item => item.Odds).Take(3).ToList();
1146 
1147                     bbet = SetIndex(bbet);
1148                     //bbet = GameHelper.AddTempLiveNumber(bbet, false, runner.ToString(), null, null, 0);
1149                     bbet = GameHelper.AddTempLiveNumber(bbet, false, runner.ToString(), null).ToList();
1150                     if (abet != null) list.AddRange(abet);
1151                     if (bbet != null) list.AddRange(bbet);
1152                 }
1153                 return list;
1154             }
1155             return null;
1156         }
1157 
1158 
1159         public static IList<LiveNumberInfoByHorse> GetTop3Horse(IList<HorseOddsKey> runnerIds)
1160         {
1161             if (runnerIds != null && runnerIds.Count > 0)
1162             {
1163                 IList<int> rid = runnerIds.Select(item => item.RunnerId).ToList();
1164                 IList<string> mid = runnerIds.Select(item => item.MarketId).ToList();
1165 
1166                 var sql = new List<IMongoQuery> { Query.EQ("Status", 0), Query.In("RunnerId", new BsonArray(rid)) };
1167 
1168                 IMongoQuery query = null;
1169                 if (sql.Count > 0)
1170                 {
1171                     query = Query.And(sql.ToArray());
1172                 }
1173 
1174                 MongoCollection col = MongoDBUtility.GetCollection(TicketHorseCollection);
1175                 if (col == null) return null;
1176 
1177                 MongoCursor<TxHorseTicketPending> m = col.FindAs<TxHorseTicketPending>(query);
1178                 var data = new List<TxHorseTicketPending>();
1179                 var list = new List<LiveNumberInfoByHorse>();
1180                 if (m != null && m.Count() > 0)
1181                 {
1182                     data.AddRange(m);
1183                 }
1184                 foreach (HorseOddsKey runner in runnerIds)
1185                 {
1186                     //获取bet部分
1187                     IList<TxHorseTicketPending> a =
1188                         data.Where(
1189                             item =>item.MarketId==runner.MarketId && item.RunnerId != null &&
1190                                 (item.RunnerId == runner.RunnerId && item.TicketType == HorseType.Bet)).ToList();
1191                     var abet = (from it in a
1192                                 group it by it.Odds
1193                                     into g
1194                                     select new LiveNumberInfoByHorse()
1195                                     {
1196                                         IsBet = true,
1197                                         GameId = runner.MarketId,
1198                                         RunId = runner.RunnerId.ToString(),
1199                                         Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1200                                         Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1201                                     }).OrderByDescending(item => item.Odds).Take(3).ToList();
1202 
1203                     abet = SetIndex(abet);
1204                     abet = GameHelper.AddTempLiveNumber(abet, true, runner.RunnerId.ToString(), runner.MarketId).ToList();
1205                     //获取eat部分
1206                     IList<TxHorseTicketPending> b =
1207                         data.Where(
1208                             item =>item.MarketId==runner.MarketId && item.RunnerId != null &&
1209                                 (item.RunnerId == runner.RunnerId && item.TicketType == HorseType.Eat)).ToList();
1210                     var bbet = (from it in b
1211                                 group it by it.Odds
1212                                     into g
1213                                     select new LiveNumberInfoByHorse()
1214                                     {
1215                                         IsBet = false,
1216                                         GameId = runner.MarketId,
1217                                         RunId = runner.RunnerId.ToString(),
1218                                         Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1219                                         Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1220                                     }).OrderBy(item => item.Odds).Take(3).ToList();
1221 
1222                     bbet = SetIndex(bbet);
1223                     //bbet = GameHelper.AddTempLiveNumber(bbet, false, runner.ToString(), null, null, 0);
1224                     bbet = GameHelper.AddTempLiveNumber(bbet, false, runner.RunnerId.ToString(), runner.MarketId).ToList();
1225                     if (abet != null) list.AddRange(abet);
1226                     if (bbet != null) list.AddRange(bbet);
1227                 }
1228                 return list;
1229             }
1230             return null;
1231         }
1232 
1233         /// <summary>
1234         /// 删除赛马的赔率
1235         /// </summary>
1236         /// <param name="query"></param>
1237         /// <returns></returns>
1238         public static bool DeteleHorseOdds(IMongoQuery query)
1239         {
1240             MongoCollection col = GetCollection(TicketHorseCollection);
1241             if (col != null)
1242             {
1243                 WriteConcernResult result = col.Remove(query);
1244                 return true;
1245             }
1246             return false;
1247         }
1248         /// <summary>
1249         /// 删除具体某匹赛马的信息
1250         /// </summary>
1251         /// <param name="query"></param>
1252         /// <returns></returns>
1253         public static bool DeteleHorseRunner(IMongoQuery query)
1254         {
1255             MongoCollection col = GetCollection(HorseRunnersCollection);
1256             if (col != null)
1257             {
1258                 WriteConcernResult result = col.Remove(query);
1259                 return true;
1260             }
1261             return false;
1262         }
1263         /// <summary>
1264         /// 删除具体某匹赛马的历史信息
1265         /// </summary>
1266         /// <param name="query"></param>
1267         /// <returns></returns>
1268         public static bool DeteleRunnerDetail(IMongoQuery query)
1269         {
1270             MongoCollection col = GetCollection(RunnerDetailCollection);
1271             if (col != null)
1272             {
1273                 WriteConcernResult result = col.Remove(query);
1274                 return true;
1275             }
1276             return false;
1277         }
1278 
1279 
1280         public static IList<TxHorseTicketPending> GetHorseListByQuery(IMongoQuery query, IMongoSortBy s)
1281         {
1282             if (query != null)
1283             {
1284                 MongoCollection col = GetCollection(TicketHorseCollection);
1285                 if (col == null) return null;
1286 
1287                 MongoCursor<TxHorseTicketPending> m = col.FindAs<TxHorseTicketPending>(query).SetSortOrder(s);
1288                 List<TxHorseTicketPending> data = new List<TxHorseTicketPending>();
1289                 if (m != null && m.Count() > 0)
1290                 {
1291                     foreach (var item in m)
1292                     {
1293                         data.Add(item);
1294                     }
1295                 }
1296                 return data;
1297             }
1298             return null;
1299         }
1300 
1301         public static TxHorseTicketPending GetOneHorse(string pendingId)
1302         {
1303             IMongoQuery query = Query.EQ("_id", ObjectId.Parse(pendingId));
1304             MongoCollection col = GetCollection(TicketHorseCollection);
1305             if (col != null)
1306             {
1307                 var result = col.FindOneAs<TxHorseTicketPending>(query);
1308                 return result;
1309             }
1310             return null;
1311         }
1312 
1313         public static bool UpdateHorse(IMongoQuery query, IMongoUpdate update)
1314         {
1315             MongoCollection col = GetCollection(TicketHorseCollection);
1316             if (col != null)
1317             {
1318                 col.Update(query, update);
1319                 return true;
1320             }
1321             return false;
1322         }
1323 
1324         public static bool DeteleHorse(IMongoQuery query)
1325         {
1326             MongoCollection col = GetCollection(TicketHorseCollection);
1327             if (col != null)
1328             {
1329                 WriteConcernResult result = col.Remove(query);
1330                 return true;
1331             }
1332             return false;
1333         }
1334 
1335         public static bool UpdateHorseList(IMongoQuery query, IMongoUpdate update)
1336         {
1337             MongoCollection col = GetCollection(TicketHorseCollection);
1338             if (col != null)
1339             {
1340                 col.Update(query, update, UpdateFlags.Multi);
1341                 return true;
1342             }
1343             return false;
1344         }
1345 
1346 
1347         #endregion
1348 
1349         #region 4D相关辅助
1350 
1351         public static IList<LiveNumberInfo> GetTop3LiveFromIList(IList<Tx4DTicketPending> data, string marketName, List<string> latters, List<int> prizes,IDictionary<string,int> latterAndNumbers )
1352           {
1353               var list = new List<LiveNumberInfo>();
1354               for (int i = 0; i < latters.Count; i++)
1355               {
1356                   string number = "0000";
1357                   if (latterAndNumbers != null && latterAndNumbers.Count > 0 && latterAndNumbers.ContainsKey(latters[i]))
1358                   {
1359                       number = latterAndNumbers[latters[i]].ToString();
1360                   }
1361 
1362                   //获取bet部分
1363                   IList<Tx4DTicketPending> a = data.Where(item => (item.BetLatter == latters[i] && item.TicketType == D4Type.RunningEat)).ToList();
1364                   var abet = (from it in a
1365                               group it by it.Odds into g
1366                               select new LiveNumberInfo()
1367                               {
1368                                   IsBet = true,
1369                                   Latter = latters[i],
1370                                   MarketName = marketName,
1371                                   Prize = prizes[i],
1372                                   Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1373                                   Number = Utility.ConvertToString(g.First().BetNumber),
1374                                   Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1375                               }).OrderByDescending(item => item.Odds).Take(3).ToList();
1376 
1377                   abet = SetIndex(abet);
1378                   if (abet != null && abet.Count > 0) number = abet[0].Number;
1379                   abet = GameHelper.AddTempLiveNumber(abet, true, latters[i], marketName, number, prizes[i]);
1380 
1381                   //获取eat部分
1382                   IList<Tx4DTicketPending> b = data.Where(item => (item.BetLatter == latters[i] && item.TicketType == D4Type.RunningBet)).ToList();
1383                   var bbet = (from it in b
1384                               group it by it.Odds into g
1385                               select new LiveNumberInfo()
1386                               {
1387                                   IsBet = false,
1388                                   Latter = latters[i],
1389                                   MarketName = marketName,
1390                                   Prize = prizes[i],
1391                                   Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1392                                   Number = Utility.ConvertToString(g.First().BetNumber),
1393                                   Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1394                               }).OrderBy(item => item.Odds).Take(3).ToList();
1395 
1396                   bbet = SetIndex(bbet);
1397                   if (bbet != null && bbet.Count > 0)
1398                   {
1399                       //number = bbet[0].MarketName;
1400                       number = bbet[0].Number;
1401                   }
1402                   bbet = GameHelper.AddTempLiveNumber(bbet, false, latters[i], marketName, number, prizes[i]);
1403 
1404                   list.AddRange(abet);
1405                   list.AddRange(bbet);
1406               }
1407               return list;
1408           }
1409 
1410         public static IList<LiveNumberInfo> Get6DTop3LiveFromIList(IList<Tx6DTicketPending> data, string marketName, string[] numbers)
1411         {
1412             var list = new List<LiveNumberInfo>();
1413 
1414             for (int i = 0; i < numbers.Length; i++)
1415             {
1416                 string number = "0000";
1417                 //获取bet部分
1418                 IList<Tx6DTicketPending> a = data.Where(item => (item.BetNumber == int.Parse(numbers[i]) && item.TicketType == D6Type.ExtraEat)).ToList();
1419                 var abet = (from it in a
1420                             group it by it.Odds into g
1421                             select new LiveNumberInfo()
1422                             {
1423                                 IsBet = true,
1424                                 Latter = numbers[i],
1425                                 MarketName = marketName,
1426                                 Prize = 0,
1427                                 Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1428                                 Number = Utility.ConvertToString(g.First().BetNumber),
1429                                 Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumEuro; }).Value, 0)
1430                             }).OrderByDescending(item => item.Odds).Take(3).ToList();
1431 
1432                 abet = SetIndex(abet);
1433                 if (abet != null && abet.Count > 0) number = abet[0].Number;
1434                 abet = GameHelper.AddTempLiveNumber(abet, true, numbers[i], marketName, numbers[i], 0);
1435 
1436                 //获取eat部分
1437                 IList<Tx6DTicketPending> b = data.Where(item => (item.BetNumber == int.Parse(numbers[i]) && item.TicketType == D6Type.ExtraBet)).ToList();
1438                 var bbet = (from it in b
1439                             group it by it.Odds into g
1440                             select new LiveNumberInfo()
1441                             {
1442                                 IsBet = false,
1443                                 Latter = numbers[i],
1444                                 MarketName = marketName,
1445                                 Prize = 0,
1446                                 Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1447                                 Number = Utility.ConvertToString(g.First().BetNumber),
1448                                 Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumEuro; }).Value, 0)
1449                             }).OrderBy(item => item.Odds).Take(3).ToList();
1450 
1451                 bbet = SetIndex(bbet);
1452                 if (bbet != null && bbet.Count > 0) number = bbet[0].MarketName;
1453                 bbet = GameHelper.AddTempLiveNumber(bbet, false, numbers[i], marketName, numbers[i], 0);
1454 
1455                 list.AddRange(abet);
1456                 list.AddRange(bbet);
1457             }
1458             return list;
1459         }
1460 
1461         public static IList<BsoeInfo> GetTop3BsoeFromIList(IList<Tx4DTicketPending> data, DateTime lotteryTime, string marketName, IList<string> ticketType)
1462         {
1463             var list = new List<BsoeInfo>();
1464 
1465             for (int i = 0; i < ticketType.Count; i++)
1466             {
1467                 //sql_zheng = sql + "ticket_type='" + D4Type.Small + "' and odds>0 order by odds asc limit 3";
1468                 //sql_fu = sql + "ticket_type='" + D4Type.Small + "' and odds<0 order by odds asc limit 3";
1469 
1470                 //获取bs部分
1471                 IList<Tx4DTicketPending> zheng = data.Where(item => (item.TicketType == GetNeedType(ticketType[i]) && item.Odds > 0)).ToList();
1472                 var z = (from it in zheng
1473                          group it by it.Odds into g
1474                          select new BsoeInfo()
1475                          {
1476                              Bsoe = GetBsoe(ticketType[i]),
1477                              MarketName = marketName,
1478                              Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1479                              Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1480                          }).OrderBy(item => item.Odds).Take(3).ToList();
1481 
1482                 if (z != null && z.Count > 0) z = SetIndex(z);
1483 
1484                 if (z.Count < 3)
1485                 {
1486                     IList<Tx4DTicketPending> fu =
1487                         data.Where(item => (item.TicketType == GetNeedType(ticketType[i]) && item.Odds < 0)).ToList();
1488                     var f = (from it in fu
1489                              group it by it.Odds
1490                                  into g
1491                                  select new BsoeInfo()
1492                                  {
1493                                      Bsoe = GetBsoe(ticketType[i]),
1494                                      MarketName = marketName,
1495                                      Odds = Utility.ConvertToDecimal(g.First().Odds, decimal.Zero),
1496                                      Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumSource; }).Value, 0)
1497                                  }).OrderBy(item => item.Odds).Take(3).ToList();
1498                     IList<BsoeInfo> result = GameHelper.AddTempBsoeInfo(CombineList(z, f, 3), marketName, GetBsoe(ticketType[i]));
1499                     result = SetIndex(result);
1500                     list.AddRange(result);
1501                 }
1502                 else
1503                 {
1504                     list.AddRange(z);
1505                 }
1506             }
1507             return list;
1508         }
1509 
1510         public static IList<HiLoInfo> GetTop3HiloFromIList(IList<Tx6DTicketPending> data, GameDrawDate drawDate)
1511         {
1512             var list = new List<HiLoInfo>();
1513             //获取high部分  //group it by it.Odds into g
1514             IList<Tx6DTicketPending> hi = data.Where(item => (item.TicketType == D6Type.Low)).ToList();
1515             var h = (from it in hi
1516                      group it by Utility.ZhiShe2(it.OddsEuro.Value) into g
1517                      select new HiLoInfo()
1518                      {
1519                          HiLo = "h",
1520                          MarketName = drawDate.SysMarket.Name,
1521                          Odds = Utility.ConvertToDecimal(Utility.ZhiShe2(g.First().OddsEuro.Value), decimal.Zero),
1522                          Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumEuro; }).Value, 0)
1523                      }).OrderByDescending(item => item.Odds).Take(3).ToList();
1524 
1525             if (h != null && h.Count > 0) h = SetIndex(h);
1526             h = Game6DHelper.AddTempHiloInfo(h, drawDate.SysMarket.Name, "h");
1527 
1528             //获取high部分
1529             IList<Tx6DTicketPending> lo = data.Where(item => (item.TicketType == D6Type.High)).ToList();
1530             var l = (from it in lo
1531                      group it by Utility.ZhiShe2(it.OddsEuro.Value) into g
1532                      select new HiLoInfo()
1533                      {
1534                          HiLo = "l",
1535                          MarketName = drawDate.SysMarket.Name,
1536                          Odds = Utility.ConvertToDecimal(Utility.ZhiShe2(g.First().OddsEuro.Value), decimal.Zero),
1537                          Num = Utility.ConvertToDecimal(g.Sum(item => { return item.NumEuro; }).Value, 0)
1538                      }).OrderByDescending(item => item.Odds).Take(3).ToList();
1539 
1540             if (l != null && l.Count > 0) l = SetIndex(l);
1541             l = Game6DHelper.AddTempHiloInfo(l, drawDate.SysMarket.Name, "l");
1542 
1543             list.AddRange(h);
1544             list.AddRange(l);
1545             return list;
1546         }
1547 
1548 
1549 
1550         private static List<LiveNumberInfoByHorse> SetIndex(List<LiveNumberInfoByHorse> list)
1551         {
1552             if (list != null && list.Count > 0)
1553             {
1554                 for (int i = 0; i < list.Count; i++)
1555                 {
1556                     list[i].Index = (i + 1);
1557                 }
1558                 return list;
1559             }
1560             return null;
1561         }
1562 
1563 
1564         private static List<LiveNumberInfo> SetIndex(List<LiveNumberInfo> list)
1565         {
1566             if (list != null && list.Count > 0)
1567             {
1568                 for (int i=0;i<list.Count;i++)
1569                 {
1570                     list[i].Index = (i + 1);
1571                 }
1572                 return list;
1573             }
1574             return null;
1575         }
1576 
1577         private static IList<BsoeInfo> SetIndex(IList<BsoeInfo> list)
1578         {
1579             if (list != null && list.Count > 0)
1580             {
1581                 for (int i = 0; i < list.Count; i++)
1582                 {
1583                     list[i].Index = (i + 1);
1584                 }
1585                 return list;
1586             }
1587             return null;
1588         }
1589 
1590         private static List<BsoeInfo> SetIndex(List<BsoeInfo> list)
1591         {
1592             if (list != null && list.Count > 0)
1593             {
1594                 for (int i = 0; i < list.Count; i++)
1595                 {
1596                     list[i].Index = (i + 1);
1597                 }
1598                 return list;
1599             }
1600             return null;
1601         }
1602 
1603         private static List<HiLoInfo> SetIndex(List<HiLoInfo> list)
1604         {
1605             if (list != null && list.Count > 0)
1606             {
1607                 for (int i = 0; i < list.Count; i++)
1608                 {
1609                     list[i].Index = (i + 1);
1610                 }
1611                 return list;
1612             }
1613             return null;
1614         }
1615 
1616         private static string GetNeedType(string type)
1617         {
1618             if (type == D4Type.Big) return D4Type.Small;
1619             if (type == D4Type.Small) return D4Type.Big;
1620             if (type == D4Type.Odd) return D4Type.Even;
1621             if (type == D4Type.Even) return D4Type.Odd;
1622             return type;
1623         }
1624 
1625         private static IList<BsoeInfo> CombineList(IList<BsoeInfo> list1, IList<BsoeInfo> list2, int limit)
1626         {
1627             if (list1 != null && list1.Count > 0)
1628             {
1629                 int index = list1.Count + 1;
1630                 for (int i = 0; i < list2.Count; i++)
1631                 {
1632                     index += i;
1633                     if (limit > 0)
1634                     {
1635                         if (list1.Count == limit)
1636                         {
1637                             return list1;
1638                         }
1639                         else
1640                         {
1641                             list2[i].Index = index;
1642                             list1.Add(list2[i]);
1643                         }
1644                     }
1645                     else
1646                     {
1647                         list2[i].Index = index;
1648                         list1.Add(list2[i]);
1649                     }
1650                 }
1651                 return list1;
1652             }
1653             return list2;
1654         }
1655 
1656         private static string GetBsoe(string type)
1657         {
1658             return type.Replace("big", "b").Replace("small", "s").Replace("odd", "o").Replace("even", "e");
1659         }
1660 
1661         #endregion
1662 
1663 
1664         #region PushMarket相关
1665 
1666         /// <summary>
1667         /// 写入或更新某个pushMarket
1668         /// </summary>
1669         /// <param name="push"></param>
1670         /// <returns></returns>
1671         public static bool push_SetOnePushMarket(PushMarket push)
1672         {
1673             if (push != null)
1674             {
1675                 MongoCollection col = GetCollection(PushCollection);
1676                 if (col != null)
1677                 {
1678                     PushMarket p = col.FindOneAs<PushMarket>(Query.EQ("GameId", push.GameId));
1679                     if (p != null && p.GameId>0)
1680                     {
1681                         return push_UpdatePushMarket(push);
1682                     }
1683                     else
1684                     {
1685                         return push_InsertPushMarket(push);
1686                     }
1687                 }
1688             }
1689             return false;
1690         }
1691 
1692         public static bool push_InsertPushMarket(PushMarket push)
1693         {
1694             if (push != null)
1695             {
1696                 MongoCollection col = GetCollection(PushCollection);
1697                 if (col != null)
1698                 {
1699                     WriteConcernResult result = col.Insert<PushMarket>(push);
1700                     return true;
1701                 }
1702             }
1703             return false;
1704         }
1705 
1706         public static bool push_UpdatePushMarket(PushMarket push)
1707         {
1708             IMongoUpdate update = Update.Set("MarketName", push.MarketName).Set("IsPushSucess", push.IsPushSucess).Set("DrawDateTime",push.DrawDateTime);
1709             IMongoQuery query = Query.EQ("GameId", push.GameId);
1710             MongoCollection col = GetCollection(PushCollection);
1711             if (col != null)
1712             {
1713                 col.Update(query, update);
1714                 return true;
1715             }
1716             return false;
1717         }
1718 
1719         public static PushMarket push_GetPushMarketByGameId(int id)
1720         {
1721             MongoCollection col = GetCollection(PushCollection);
1722             if (col != null)
1723             {
1724                 PushMarket p = col.FindOneAs<PushMarket>(Query.EQ("GameId", id));
1725                 return p;
1726             }
1727             return null;
1728         }
1729 
1730         /// <summary>
1731         /// 获取最接近的开奖日期
1732         /// </summary>
1733         /// <returns></returns>
1734         public static IList<PushMarket> push_GetMarkets()
1735         {
1736             MongoCollection col = GetCollection(PushCollection);
1737             if (col != null)
1738             {
1739                 IMongoQuery query = Query.And(Query.LTE("DrawDateTime", DateTime.Now), Query.EQ("IsPushSucess", 0));
1740                 MongoCursor<PushMarket> m = col.FindAs<PushMarket>(query);
1741                 List<PushMarket> data = new List<PushMarket>();
1742                 if (m != null && m.Count() > 0)
1743                 {
1744                     foreach (var item in m)
1745                     {
1746                         data.Add(item);
1747                     }
1748                 }
1749                 return data;
1750             }
1751             return null;
1752         }
1753 
1754         #endregion
1755     }
1756 
1757     
1758 }
参考项目01
  1 using System.Collections.Generic;
  2 using System.Linq;
  3 using System.Web.UI;
  4 using Common.Logging;
  5 using MongoDB.Bson;
  6 using MongoDB.Driver.Linq;
  7 using NHibernate.Proxy;
  8 using TX.Common.BT;
  9 using TX.Common.Dao;
 10 using TX.Common.Domain;
 11 using System;
 12 using MongoDB.Driver;
 13 using MongoDB.Driver.Builders;
 14 using TX.Common.Tool;
 15 using TX.Common.Web;
 16 
 17 namespace TX.Common.Util
 18 {
 19     /// <summary>
 20     /// HorseSetting相关辅助操作类
 21     /// </summary>
 22     public class HorseDataUtils
 23     {
 24 
 25         #region 属性
 26 
 27         private static ILog log = LogManager.GetLogger("");
 28         private static string MarketCollection = "HorseMarket";
 29         private static string OddsCollection = "HorseOdds";
 30 
 31         private static string PendingCollection = "TxHorseTicketPending";
 32 
 33 
 34         private static string HorseRunnersCollection = "HorseRunners";
 35 
 36         /// <summary>
 37         /// 用来存储某个runner的过往历史和当前的走势
 38         /// </summary>
 39         private static string RunnerDetailCollection = "RunnerDetail";
 40 
 41         #endregion
 42 
 43         /// <summary>
 44         /// 构造函数
 45         /// </summary>
 46         public HorseDataUtils()
 47         {
 48         }
 49 
 50 
 51         #region horserunners相关
 52 
 53         public IList<RunnerDescription> GetHorseRunnersList()
 54         {
 55             IList<RunnerDescription> list = new List<RunnerDescription>();
 56             MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
 57             if (col == null) return null;
 58             MongoCursor<RunnerDescription> m = col.FindAllAs<RunnerDescription>();
 59             if (m != null && m.Count() > 0)
 60             {
 61                 foreach (var item in m)
 62                 {
 63                     list.Add(item);
 64                 }
 65             }
 66             return list;
 67         }
 68 
 69         /// <summary>
 70         /// 通过某个id获取对应方案的详细数据
 71         /// </summary>
 72         /// <param name="id"></param>
 73         /// <returns></returns>
 74         public RunnerDescription GetHorseRunnersById(string id)
 75         {
 76             if (!string.IsNullOrWhiteSpace(id))
 77             {
 78                 IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id));
 79                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
 80                 if (col != null)
 81                 {
 82                     var result = col.FindOneAs<RunnerDescription>(query);
 83                     return result;
 84                 }
 85             }
 86             return null;
 87         }
 88 
 89         public IList<RunnerDescription> GetHorseRunnersByMarketId(string id)
 90         {
 91             if (!string.IsNullOrWhiteSpace(id))
 92             {
 93                 IMongoQuery query = Query.EQ("MarketId", id);
 94 
 95                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
 96                 if (col != null)
 97                 {
 98                     var result = col.FindAs<RunnerDescription>(query);
 99                     IList<RunnerDescription> list = new List<RunnerDescription>();
100                     if (result != null && result.Count() > 0)
101                     {
102                         foreach (var item in result)
103                         {
104                             list.Add(item);
105                         }
106                     }
107                     return list;
108                 }
109             }
110             return null;
111         }
112 
113         public RunnerDescription GetHorseRunnersByMarketIdAndRunnerId(string id, long runnerId)
114         {
115             if (!string.IsNullOrWhiteSpace(id))
116             {
117                 IMongoQuery query = Query.And(Query.EQ("MarketId", id), Query.EQ("SelectionId", runnerId));
118 
119                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
120                 if (col != null)
121                 {
122                     var result = col.FindOneAs<RunnerDescription>(query);
123                     return result;
124                 }
125             }
126             return null;
127         }
128 
129 
130 
131         /// <summary>
132         /// 编辑或添加odds setting对象
133         /// </summary>
134         /// <param name="odds"></param>
135         /// <returns></returns>
136         public string UpdateHorseRunners(RunnerDescription market)
137         {
138             if (market != null)
139             {
140                 var obj = GetHorseRunnersByMarketIdAndRunnerId(market.MarketId, market.SelectionId);
141                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
142                 if (col != null)
143                 {
144                     if (obj == null)
145                     {
146                         if (market._id.ToString().StartsWith("000000"))
147                         {
148                             market._id = ObjectId.GenerateNewId();
149                         }
150                         WriteConcernResult result = col.Insert<RunnerDescription>(market);
151                         return market._id.ToString();
152                     }
153                     else
154                     {
155                         IMongoQuery query = Query.EQ("_id", market._id);
156                         var update = Update.Set("MarketId", market.MarketId);
157                         update.Set("SelectionId", market.SelectionId);
158                         update.Set("RunnerName", market.RunnerName);
159                         update.Set("Handicap", market.Handicap);
160                         update.Set("SortPriority", market.SortPriority);
161                         update.SetWrapped("Metadata", market.Metadata);
162                         col.Update(query, update);
163                     }
164                 }
165             }
166             return null;
167         }
168 
169 
170         public void UpdateHorseRunners(IList<RunnerDescription> runners)
171         {
172             if (runners != null && runners.Count > 0)
173             {
174                 MongoCollection col = MongoDBUtility.GetCollection(HorseRunnersCollection);
175                 if (col == null) return;
176                 IList<long> rids = runners.Select(item => item.SelectionId).ToList();
177 
178                 MongoCursor<RunnerDescription> m = col.FindAs<RunnerDescription>(Query.In("SelectionId", new BsonArray(rids)));
179                 List<RunnerDescription> list = new List<RunnerDescription>();
180                 if (m != null && m.Count() > 0)
181                 {
182                     list.AddRange(m);
183                 }
184                 IList<RunnerDescription> insert = new List<RunnerDescription>();
185                 IList<RunnerDescription> update = new List<RunnerDescription>();
186                 foreach (var runner in runners)
187                 {
188                     string id = IsExist(list, runner.MarketId, runner.SelectionId);
189                     if (!string.IsNullOrWhiteSpace(id))
190                     {
191                         runner._id = ObjectId.Parse(id);
192                         update.Add(runner);
193                     }
194                     else
195                     {
196                         runner._id = ObjectId.GenerateNewId();
197                         insert.Add(runner);
198                     }
199                 }
200                 if (insert.Count > 0)
201                 {
202                     col.InsertBatch<RunnerDescription>(insert);
203                 }
204                 if (update.Count > 0)
205                 {
206                     foreach (var runner in update)
207                     {
208                         IMongoQuery query = Query.EQ("_id", runner._id);
209                         var update1 = Update.Set("Handicap", runner.Handicap);
210                         update1.Set("SortPriority", runner.SortPriority);
211                         update1.SetWrapped("Metadata", runner.Metadata);
212                         col.Update(query, update1);
213                     }
214                 }
215             }
216         }
217 
218         private string IsExist(IList<RunnerDescription> list, string marketId, long selectionId)
219         {
220             if (list != null && list.Count > 0)
221             {
222                 IList<RunnerDescription> tmp = list.Where(item => item.MarketId == marketId && item.SelectionId == selectionId).ToList();
223                 if (tmp != null && tmp.Count > 0) return tmp[0]._id.ToString();
224             }
225             return null;
226         }
227         #endregion
228 
229 
230 
231         #region market相关
232 
233         /// <summary>
234         /// 获取odds setting集合
235         /// </summary>
236         /// <returns></returns>
237         public IList<MarketCatalogue> GetMarketList()
238         {
239             IList<MarketCatalogue> list = new List<MarketCatalogue>();
240             MongoCollection col = MongoDBUtility.GetCollection(MarketCollection);
241             if (col == null) return null;
242             MongoCursor<MarketCatalogue> m = col.FindAllAs<MarketCatalogue>();
243             if (m != null && m.Count() > 0)
244             {
245                 foreach (var item in m)
246                 {
247                     list.Add(item);
248                 }
249             }
250             return list;
251         }
252 
253         /// <summary>
254         /// 通过某个id获取对应方案的详细数据
255         /// </summary>
256         /// <param name="id"></param>
257         /// <returns></returns>
258         public MarketCatalogue GetMarketById(string id)
259         {
260             if (!string.IsNullOrWhiteSpace(id))
261             {
262                 IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id));
263                 MongoCollection col = MongoDBUtility.GetCollection(MarketCollection);
264                 if (col != null)
265                 {
266                     var result = col.FindOneAs<MarketCatalogue>(query);
267                     return result;
268                 }
269             }
270             return null;
271         }
272 
273         public MarketCatalogue GetMarketByMarketId(string id)
274         {
275             if (!string.IsNullOrWhiteSpace(id))
276             {
277                 IMongoQuery query = Query.EQ("MarketId", id);
278                 MongoCollection col = MongoDBUtility.GetCollection(MarketCollection);
279                 if (col != null)
280                 {
281                     var result = col.FindOneAs<MarketCatalogue>(query);
282                     return result;
283                 }
284             }
285             return null;
286         }
287 
288         /// <summary>
289         /// 编辑或添加odds setting对象
290         /// </summary>
291         /// <param name="odds"></param>
292         /// <returns></returns>
293         public string UpdateMarket(MarketCatalogue market)
294         {
295             if (market != null)
296             {
297                 MongoCollection col = MongoDBUtility.GetCollection(MarketCollection);
298                 if (col != null)
299                 {
300                     if (market._id.ToString().StartsWith("000000"))
301                     {
302                         market._id = ObjectId.GenerateNewId();
303                     }
304                     WriteConcernResult result = col.Insert<MarketCatalogue>(market);
305                     return market._id.ToString();
306                 }
307             }
308             return null;
309         }
310 
311 
312         #endregion
313 
314         #region odds 相关
315 
316         /// <summary>
317         /// 获取risk setting集合
318         /// </summary>
319         /// <returns></returns>
320         public IList<MarketBook> GetOddsList()
321         {
322             IList<MarketBook> list = new List<MarketBook>();
323             MongoCollection col = MongoDBUtility.GetCollection(OddsCollection);
324             if (col == null) return null;
325             MongoCursor<MarketBook> m = col.FindAllAs<MarketBook>();
326             if (m != null && m.Count() > 0)
327             {
328                 foreach (var item in m)
329                 {
330                     list.Add(item);
331                 }
332             }
333             return list;
334         }
335 
336         /// <summary>
337         /// 通过某个id获取对应方案的详细数据
338         /// </summary>
339         /// <param name="id"></param>
340         /// <returns></returns>
341         public MarketBook GetOddsById(string id)
342         {
343             if (!string.IsNullOrWhiteSpace(id))
344             {
345                 IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id));
346                 MongoCollection col = MongoDBUtility.GetCollection(OddsCollection);
347                 if (col != null)
348                 {
349                     var result = col.FindOneAs<MarketBook>(query);
350                     return result;
351                 }
352             }
353             return null;
354         }
355 
356         public MarketBook GetOddsByMarketId(string id)
357         {
358             if (!string.IsNullOrWhiteSpace(id))
359             {
360                 IMongoQuery query = Query.EQ("MarketId", id);
361                 MongoCollection col = MongoDBUtility.GetCollection(OddsCollection);
362                 if (col != null)
363                 {
364                     var result = col.FindOneAs<MarketBook>(query);
365                     return result;
366                 }
367             }
368             return null;
369         }
370 
371         /// <summary>
372         /// 编辑或添加Risk setting对象
373         /// </summary>
374         /// <param name="risk"></param>
375         /// <returns></returns>
376         public string UpdateOdds(MarketBook odds)
377         {
378             if (odds != null)
379             {
380                 MongoCollection col = MongoDBUtility.GetCollection(OddsCollection);
381                 if (col != null)
382                 {
383                     if (odds._id.ToString().StartsWith("00000"))
384                     {
385                         odds._id = ObjectId.GenerateNewId();
386                     }
387                     WriteConcernResult result = col.Insert<MarketBook>(odds);
388                     return odds._id.ToString();
389                 }
390             }
391             return null;
392         }
393 
394         #endregion
395 
396         #region horse ticket pending 相关
397 
398         /// <summary>
399         /// 获取risk setting集合
400         /// </summary>
401         /// <returns></returns>
402         public IList<TxHorseTicketPending> GetPendingList()
403         {
404             IList<TxHorseTicketPending> list = new List<TxHorseTicketPending>();
405             MongoCollection col = MongoDBUtility.GetCollection(PendingCollection);
406             if (col == null) return null;
407             MongoCursor<TxHorseTicketPending> m = col.FindAllAs<TxHorseTicketPending>();
408             if (m != null && m.Count() > 0)
409             {
410                 foreach (var item in m)
411                 {
412                     list.Add(item);
413                 }
414             }
415             return list;
416         }
417 
418         /// <summary>
419         /// 通过某个id获取对应方案的详细数据
420         /// </summary>
421         /// <param name="id"></param>
422         /// <returns></returns>
423         public TxHorseTicketPending GetPendingById(string id)
424         {
425             if (!string.IsNullOrWhiteSpace(id))
426             {
427                 IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id));
428                 MongoCollection col = MongoDBUtility.GetCollection(PendingCollection);
429                 if (col != null)
430                 {
431                     var result = col.FindOneAs<TxHorseTicketPending>(query);
432                     return result;
433                 }
434             }
435             return null;
436         }
437 
438         public TxHorseTicketPending GetPendingByMarketId(string id)
439         {
440             if (!string.IsNullOrWhiteSpace(id))
441             {
442                 IMongoQuery query = Query.EQ("MarketId", id);
443                 MongoCollection col = MongoDBUtility.GetCollection(PendingCollection);
444                 if (col != null)
445                 {
446                     var result = col.FindOneAs<TxHorseTicketPending>(query);
447                     return result;
448                 }
449             }
450             return null;
451         }
452 
453         /// <summary>
454         /// 编辑或添加Risk setting对象
455         /// </summary>
456         /// <param name="risk"></param>
457         /// <returns></returns>
458         public string UpdatePending(TxHorseTicketPending pending)
459         {
460             if (pending != null)
461             {
462                 MongoCollection col = MongoDBUtility.GetCollection(PendingCollection);
463                 if (col != null)
464                 {
465                     if (pending._id.ToString().StartsWith("00000"))
466                     {
467                         pending._id = ObjectId.GenerateNewId();
468                     }
469                     WriteConcernResult result = col.Insert<TxHorseTicketPending>(pending);
470                     return pending._id.ToString();
471                 }
472             }
473             return null;
474         }
475 
476         public bool UpdatePending(IList<TxHorseTicketPending> list, ref System.Exception e)
477         {
478             if (list != null && list.Count > 0)
479             {
480                 try
481                 {
482                     var group = list.GroupBy(g => new { g.RunnerId, g.MarketId }, g => { return g; }).ToList();
483                     if (group.Count > 0)
484                     {
485                         MongoCollection col = MongoDBUtility.GetCollection(PendingCollection);
486                         if (col != null)
487                         {
488                             foreach (var item in group)
489                             {
490                                 IList<TxHorseTicketPending> runnerTickets = item.ToList();
491                                 if (runnerTickets != null && runnerTickets.Count > 0)
492                                 {
493                                     IMongoQuery query = Query.And(Query.EQ("RunnerId", runnerTickets[0].RunnerId), Query.EQ("MarketId", runnerTickets[0].MarketId));
494                                     col.Remove(query);//先删除该节点下的赔率,然后插入新赔率数据
495                                     for (int i = 0; i < runnerTickets.Count; i++)
496                                     {
497                                         if (runnerTickets[i]._id.ToString().StartsWith("00000"))
498                                         {
499                                             runnerTickets[i]._id = ObjectId.GenerateNewId();
500                                         }
501                                     }
502                                     col.InsertBatch<TxHorseTicketPending>(runnerTickets);
503                                 }
504                             }
505                             return true;
506                         }
507                     }
508                 }
509                 catch (System.Exception err)
510                 {
511                     e = err;
512                     log.Error(err);
513                 }
514             }
515             return false;
516         }
517 
518         #endregion
519 
520         #region runner detail相关
521 
522         /// <summary>
523         /// 通过某个id获取对应方案的详细数据
524         /// </summary>
525         /// <param name="id"></param>
526         /// <returns></returns>
527         public RunnerDetail GetRunnerDetailById(string id)
528         {
529             if (!string.IsNullOrWhiteSpace(id))
530             {
531                 IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id));
532                 MongoCollection col = MongoDBUtility.GetCollection(RunnerDetailCollection);
533                 if (col != null)
534                 {
535                     var result = col.FindOneAs<RunnerDetail>(query);
536                     return result;
537                 }
538             }
539             return null;
540         }
541 
542         /// <summary>
543         /// 通过marketId,selectionId/runnerId获取对象
544         /// </summary>
545         /// <param name="marketId"></param>
546         /// <param name="runnerId"></param>
547         /// <returns></returns>
548         public RunnerDetail GetRunnerDetailById(string marketId, string runnerId)
549         {
550             if (!string.IsNullOrWhiteSpace(marketId) && !string.IsNullOrWhiteSpace(runnerId))
551             {
552                 IMongoQuery query = Query.And(Query.EQ("MarketId", marketId), Query.EQ("SelectionId", runnerId));
553                 MongoCollection col = MongoDBUtility.GetCollection(RunnerDetailCollection);
554                 if (col != null)
555                 {
556                     var result = col.FindOneAs<RunnerDetail>(query);
557                     return result;
558                 }
559             }
560             return null;
561         }
562 
563         /// <summary>
564         /// 编辑或添加runnerDetail对象
565         /// </summary>
566         /// <param name="risk"></param>
567         /// <returns></returns>
568         public string UpdateRunnerDetail(RunnerDetail detail, ref bool isSend)
569         {
570             if (detail != null)
571             {
572                 MongoCollection col = MongoDBUtility.GetCollection(RunnerDetailCollection);
573                 if (col != null)
574                 {
575                     if (detail._id.ToString().StartsWith("00000"))
576                     {
577                         detail._id = ObjectId.GenerateNewId();
578                     }
579                     RunnerDetail rd = null;
580                     if (!string.IsNullOrWhiteSpace(detail.MarketId) && !string.IsNullOrWhiteSpace(detail.SelectionId))
581                     {
582                         rd = GetRunnerDetailById(detail.MarketId, detail.SelectionId);
583                     }
584                     if (rd == null)
585                     {
586                         WriteConcernResult result = col.Insert<RunnerDetail>(detail);
587                     }
588                     else
589                     {
590                         IMongoQuery query = Query.And(Query.EQ("MarketId", rd.MarketId), Query.EQ("SelectionId", rd.SelectionId));
591                         var update = Update.Set("Html", NotNull(detail.Html)).Set("NotInverseAIName", NotNull(detail.NotInverseAIName)).Set("Remark", NotNull(detail.Remark)).Set("IsInverseAIName", NotNull(detail.IsInverseAIName)).Set("Percent", NotNull(detail.Percent));
592                         WriteConcernResult result = col.Update(query, update);
593 
594                         if (!string.IsNullOrWhiteSpace(detail.Percent) && rd.Percent != detail.Percent)
595                         {
596                             isSend = true;
597                         }
598                     }
599                     return detail._id.ToString();
600                 }
601             }
602             return null;
603         }
604 
605         private string NotNull(string txt)
606         {
607             if (!string.IsNullOrWhiteSpace(txt)) return txt;
608             return "-";
609         }
610 
611         #endregion
612 
613     }
614 }
参考项目02

多条件 IMongoQuery query = Query.And(Query.EQ("MarketId", id), Query.EQ("SelectionId", runnerId));

 补充:Query.In()方法应用

第二种写法:把数组或集合变成一个BsonArray数组
IList<long> rids = runners.Select(item => item.SelectionId).ToList();
MongoCursor<RunnerDescription> m =col.FindAs<RunnerDescription>(Query.In("SelectionId", new BsonArray(rids)));

posted on 2015-03-21 16:52  高达  阅读(837)  评论(0)    收藏  举报

导航