如何使用 java 獲取所有 MongoDB 資料庫的列表?


在 MongoDB 中,你可以使用 show dbs 命令來檢視資料庫列表

> show dbs
admin
config
local
myDatabase
sampleDatabase
students
test
testDB

在 Java 中,你可以使用 getDatabaseNames() 方法獲取 MongoDB 中的所有資料庫列表。

示例

import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;
public class ListOfDatabases {
   public static void main( String args[] ) {
      // Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Retrieving the list of collections
      MongoIterable<String> list = mongo.listDatabaseNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

輸出

admin
config
local
myDatabase
sampleDatabase
students
test
testDB

更新於: 2020 年 4 月 10 日

898 檢視次數

啟動你的 職業

透過完成課程獲取證書

開始
廣告
© . All rights reserved.