如何使用 Java 列出 MongoDB 資料庫中的所有集合?
可以使用show collections列印資料庫中所有現有集合的列表。
示例
假設我們在 MongoDB 資料庫中建立了 3 個集合,如下所示 −
> use sampleDatabase
switched to db sampleDatabase
> db.createCollection("students")
{ "ok" : 1 }
> db.createCollection("teachers")
{ "ok" : 1 }
> db.createCollection("sample")
{ "ok" : 1 }以下查詢列出了資料庫中的所有集合 −
> use sampleDatabase switched to db sampleDatabase > show collections sample students teachers
利用 Java 程式
在 Java 中,可以使用com.mongodb.client.MongoCollection 介面的 listCollectionNames()方法獲取當前資料庫中的所有集合名稱。
因此,使用 Java 程式在 MongoDB 中列出資料庫中的所有集合 −
確保已在系統中安裝 MongoDB
將以下依賴項新增到 Java 專案的 pom.xml 檔案中。
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency>
透過例項化 MongoClient 類建立 MongoDB 客戶端。
使用 getDatabase()方法連線到資料庫。
使用 listCollectionNames()方法獲取集合列表。
示例
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;
public class ListOfCollection {
public static void main( String args[] ) {
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Connecting to the database
MongoDatabase database = mongo.getDatabase("mydatabase");
//Creating multiple collections
database.createCollection("sampleCollection1");
database.createCollection("sampleCollection2");
database.createCollection("sampleCollection3");
database.createCollection("sampleCollection4");
//Retrieving the list of collections
MongoIterable<String> list = database.listCollectionNames();
for (String name : list) {
System.out.println(name);
}
}
}輸出
sampleCollection3 sampleCollection2 sampleCollection4 sampleCollection1
廣告
資料結構
網路技術
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP