gpt4 book ai didi

c# - 如何在C#中获取连接字符串中指定的Mongo数据库

转载 作者:IT老高 更新时间:2023-10-28 11:16:34 24 4
gpt4 key购买 nike

我想连接到连接字符串中指定的数据库,而不是在 GetDatabase 中再次指定它。

例如,如果我有这样的连接字符串;

mongodb://localhost/mydb

我希望能够从 mydb 获取 db.GetCollection("mycollection")

这将允许在 app.config 文件中轻松配置数据库名称。

最佳答案

更新:

MongoServer.Create 现在已经过时了(感谢@aknuds1)。而是使用以下代码:

var _server = new MongoClient(connectionString).GetServer();

这很容易。您应该首先从连接字符串中获取数据库名称,然后按名称获取数据库。完整示例:

var connectionString = "mongodb://localhost:27020/mydb";

//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);

//and then get database by database name:
_server.GetDatabase(_databaseName);

重要提示:如果您的数据库和auth 数据库不同,您可以添加一个authSource= 查询参数来指定不同的auth 数据库。 (感谢@chrisdrobison)

From docs:

NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.

关于c# - 如何在C#中获取连接字符串中指定的Mongo数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7201847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com