您可以使用显示集合来打印数据库中所有现有集合的列表。
假设我们在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中,您可以使用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[] ) {
//创建一个Mongo客户端
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//连接到数据库
MongoDatabase database = mongo.getDatabase("mydatabase");
//创建多个集合
database.createCollection("sampleCollection1");
database.createCollection("sampleCollection2");
database.createCollection("sampleCollection3");
database.createCollection("sampleCollection4");
//检索收藏列表
MongoIterable<String> list = database.listCollectionNames();
for (String name : list) {
System.out.println(name);
}
}
}
sampleCollection3
sampleCollection2
sampleCollection4
sampleCollection1