我遇到了很多连接被打开到mongo db的问题。
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 :(得分:1)
迟到的答案......但此时创建了服务器连接:
var client = new MongoClient("mongodb://localhost:27017");
其他一切只是获取各种对象的参考。
请参阅:http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-csharp-driver/
答案 1 :(得分:0)
在为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服务器并使用断点调试代码后,我发现了这一点。初始化顺利进行,但在db操作时抛出了错误。
希望这有帮助。