简体   繁体   English

如何通过在 mongo C# 驱动程序中仅使用连接字符串来`ListCollections`?

[英]How to `ListCollections` by using only connection string in mongo C# driver?

I'm instantiating MongoClient with full connection string which includes DB :我正在使用包含 DB 的完整连接字符串实例化MongoClient

MongoClient dbClient = new MongoClient("mongodb://***:***@***:27017/myDb");
var dbList = dbClient.ListDatabases();
IMongoDatabase db = dbClient.GetDatabase("myDb");
var collList = db.ListCollections().ToList();
... 

This works.这有效。 But -但 -

If the connection string already includes myDb , then why do I need to write again :如果连接字符串已经包含myDb ,那么为什么我需要再次写入:

dbClient.GetDatabase("myDb");

? ?

I've already written myDb in the connection string.我已经在连接字符串中写入了myDb

Question:题:

Is there any option to ListCollections of the DB which already mentioned in the connection string?连接字符串中已经提到的 DB 的ListCollections是否有任何选项?

One option is to just pull out the database name from the connection string.一种选择是从连接字符串中提取数据库名称。 That might sound a bit messy, but MongoUrl makes it nice and easy.这听起来可能有点乱,但MongoUrl变得简单又好用。 Here's an example:下面是一个例子:

var connectionString = "...";
var dbName = MongoUrl.Create(connectionString).DatabaseName;

// ...

IMongoDatabase db = dbClient.GetDatabase(dbName);

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

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