繁体   English   中英

MongoDB C#驱动程序什么时候打开连接?

[英]At what point does the MongoDB C# driver open a connection?

我在与mongo db打开许多连接时遇到问题。

Github页面上C#驱动程序的自述文件提供了以下代码:

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()方法?

我知道我们应该为客户端提供一个静态对象,但是我们也应该为服务器和数据库提供一个静态对象吗?

较晚的答案...但是此时已创建服务器连接:

 var client = new MongoClient("mongodb://localhost:27017");

其他一切都只是获取各种对象的引用。

请参阅: http : //docs.mongodb.org/ecosystem/tutorial/getting-started-with-csharp-driver/

对于C#使用最新的MongoDB驱动程序时,连接发生在实际的数据库操作中。 例如。 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服务器并使用断点调试代码后才发现这一点。 初始化进行得很顺利,但是在数据库操作中引发了错误。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM