UFO ET IT

C #의 연결 문자열에 지정된 Mongo 데이터베이스를 가져 오는 방법

ufoet 2021. 1. 15. 07:42
반응형

C #의 연결 문자열에 지정된 Mongo 데이터베이스를 가져 오는 방법


에서 다시 지정하지 않고 연결 문자열에 지정된 데이터베이스에 연결하고 싶습니다 GetDatabase.

예를 들어 다음과 같은 연결 문자열이있는 경우;

mongodb://localhost/mydb

db.GetCollection("mycollection")에서 할 수 있기 를 바랍니다 mydb.

이렇게하면 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);

중요 : 데이터베이스와 인증 데이터베이스가 다른 경우 authSource = 쿼리 매개 변수를 추가하여 다른 인증 데이터베이스를 지정할 수 있습니다. ( @chrisdrobison 에게 감사드립니다 )

문서에서 :

참고 데이터베이스 세그먼트를 사용할 초기 데이터베이스로 사용하고 있지만 지정된 사용자 이름과 암호가 다른 데이터베이스에 정의되어있는 경우 authSource 옵션을 사용하여 자격 증명이 정의 된 데이터베이스를 지정할 수 있습니다. 예를 들어 mongodb : // user : pass @ hostname / db1? authSource = userDb는 db1 대신 userDb 데이터베이스에 대해 자격 증명을 인증합니다.


이 순간에 C # 드라이버의 마지막 버전 (2.3.0)에서 연결 문자열에 지정된 데이터베이스 이름을 얻는 유일한 방법은 다음과 같습니다.

var connectionString = @"mongodb://usr:pwd@srv1.acme.net,srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";
var mongoUrl = new MongoUrl(connectionString);
var dbname = mongoUrl.DatabaseName;
var db = new MongoClient(mongoUrl).GetDatabase(dbname);
db.GetCollection<MyType>("myCollectionName");

공식 10gen 드라이버 버전 1.7에서 다음은 현재 (구식되지 않은) API입니다.

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

아래의 대답은 지금은 쓸모가 없지만 구형 드라이버에서 작동합니다. 주석을 참조하십시오.

연결 문자열이있는 경우 MongoDatabase를 직접 사용할 수도 있습니다.

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

참조 URL : https://stackoverflow.com/questions/7201847/how-to-get-the-mongo-database-specified-in-connection-string-in-c-sharp

반응형