Check if mongodb database exists?

前端 未结 9 1509
孤街浪徒
孤街浪徒 2020-12-14 21:58

Is there a possibility to check if a mongo database allready exists?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 22:43

    In my case, I could not use listDatabaseNames, because my user did not have the rights to call this function. Instead, I just assume that it exists and call a method on this database, which will fail if it does not exist or if rights are missing.

    Demo C# code:

    /// 
    /// Tests the connection to the MongoDB server, and if the database already exists.
    /// If not or an error is detected, an exception is thrown.
    /// 
    public static void TestConnection(string mongoUrl, string mongoDatabase) {
       var client = new MongoClient(mongoUrl);
       var database = client.GetDatabase(mongoDatabase);
       try {
          // Try to perform an action on this database; will fail if it does not exist
          database.ListCollections(); 
       }
       catch {
          throw new Exception("Connection established, " +
             "but database does not exist (or missing rights): " + mongoDatabase);
       }    
    }
    

提交回复
热议问题