如何使用 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