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

我想连接到连接字符串中指定的数据库,而不是在 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.

https://stackoverflow.com/questions/7201847/

相关文章:

mongodb - 通过键字段查找 MongoDB 集合中的所有重复文档

c# - 将字符串转换为 MongoDB BsonDocument

node.js - Meteor - collection.find() 总是返回所有字段

mongodb - 同一台服务器上的多个 Mongodb 实例

mongodb - 在 MongoDB 中克隆一个集合

mongodb - 从 Mongoose 模型中获取模式属性

node.js - 如何设置 useMongoClient (Mongoose 4.11.0)?

javascript - 从 mongodb id 获取时间戳

node.js - Express.js 在 MEAN 堆栈中做了什么?

mongodb - Mongo,通过 id 列表查找