如何获得在C#中的连接字符串指定的数据库蒙戈 [英] How to get the Mongo database specified in connection string in C#

查看:480
本文介绍了如何获得在C#中的连接字符串指定的数据库蒙戈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to connect to the database specified in the connection string, without specifying it again in GetDatabase.

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

For example, if I have a connection string like this;

mongodb://localhost/mydb

我想能够 db.GetCollection从 MYDB (MyCollection的)

I would like to be able to db.GetCollection("mycollection") from mydb.

这将使数据库名称app.config文件中轻松进行配置。

This would allow the database name to be configured easily in the app.config file.

推荐答案

更新:

MongoServer.Create 现在已经过时了(感谢@ aknuds1)。相反,这种使用下面的代码:

MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

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






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


It's easy. You should first take database name from connection string and then get database by name. Complete example:

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);

重要提示:如果您的数据库和权威性的数据库不同,您可以添加一个authSource =查询参数指定不同的身份验证数据库。 (谢谢 @chrisdrobison

Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

From文档:

请注意如果您正在使用的数据库段作为初始数据库
使用,但指定的用户名和密码在
不同的数据库中定义,你可以使用authSource选项来指定$ b $其中凭证定义b数据库。例如,
的mongodb://用户:?通过@主机名/ DB1 authSource = USERDB将验证
对USERDB数据库,而不是DB1凭证

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#中的连接字符串指定的数据库蒙戈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆