2014-09-30 94 views
0

我遇到了很多打开到mongo db的连接问题。MongoDB C#驱动程序在什么时候打开连接?

自述在Github page for the C# driver给出了下面的代码:

using MongoDB.Bson; 
using MongoDB.Driver; 
var client = new MongoClient("mongodb://localhost:27017"); 
var server = client.GetServer(); 
var database = server.GetDatabase("foo"); 
var collection = database.GetCollection("bar"); 

collection.Insert(new BsonDocument("Name", "Jack")); 

foreach(var document in collection.FindAll()) 
{ 
    Console.WriteLine(document["Name"]); 
} 

在什么时候司机开到服务器的连接?它是在GetServer()方法还是在Insert()方法?

我知道我们应该有一个客户端的静态对象,但是我们是否也有一个服务器和数据库的静态对象呢?

+0

难道你不能找到一些调试打印语句(或断点)和检查当前连接吗?或者,通过使mongod不可用并查看它抛出错误的位置来使连接失败。 – 2014-10-01 08:53:43

+0

连接在Insert方法下打开。驾驶员下方有一个游泳池,因此“大量连接”有点模糊。你能更精确吗? – 2014-10-13 14:33:49

回答

0

,连接发生在实际的数据库操作。例如。 db.Collection.Find()或db.collection.InsertOne()。

{ 
    //code for initialization 
    //for localhost connection there is no need to specify the db server url and port. 
    var client = new MongoClient("mongodb://localhost:27017/"); 
    var db = client.GetDatabase("TestDb"); 
    Collection = db.GetCollection<T>("testCollection"); 
} 
//Code for db operations 
{ 

    //The connection happens here. 
    var collection = db.Collection; 
    //Your find operation 
    var model = collection.Find(Builders<Model>.Filter.Empty).ToList(); 
    //Your insert operation 
    collection.InsertOne(Model); 
} 

我发现了这一点我停在我的mongod服务器和调试用的断点的代码之后。初始化过程很顺利,但在数据库操作中引发了错误。

希望这会有所帮助。

相关问题