Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách liệt kê tất cả Collection trong database MongoDB bằng Java


Bạn có thể in danh sách tất cả collection hiện có trong database bằng lệnh show collections.

Ví dụ

Giả sử chúng ta đã tạo 3 collection trong database MongoDB như sau:

> use sampleDatabase
switched to db sampleDatabase
> db.createCollection("students")
{ "ok" : 1 }
> db.createCollection("teachers")
{ "ok" : 1 }
> db.createCollection("sample")
{ "ok" : 1 }

Truy vấn sau liệt kê tất cả collection trong database:

> use sampleDatabase
switched to db sampleDatabase
> show collections
sample students teachers

Sử dụng chương trình Java

Trong Java, bạn có thể lấy tên tất cả collection trong database hiện tại bằng phương thức listCollectionNames() của interface com.mongodb.client.MongoCollection.

Do đó, để liệt kê tất cả collection trong database MongoDB bằng Java:

  • Đảm bảo bạn đã cài đặt MongoDB trên hệ thống.

  • Thêm dependency sau vào file pom.xml của dự án Java.

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.2</version>
</dependency>
  • Tạo MongoDB client bằng cách khởi tạo lớp MongoClient.

  • Kết nối đến database bằng phương thức getDatabase().

  • Lấy danh sách collection bằng phương thức listCollectionNames().

Ví dụ

import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;

public class ListOfCollection {
public static void main(String args[]) {
// Tạo Mongo client
MongoClient mongo = new MongoClient("localhost", 27017);
// Kết nối đến database
MongoDatabase database = mongo.getDatabase("mydatabase");
// Tạo nhiều collection
database.createCollection("sampleCollection1");
database.createCollection("sampleCollection2");
database.createCollection("sampleCollection3");
database.createCollection("sampleCollection4");
// Lấy danh sách collection
MongoIterable<String> list = database.listCollectionNames();
for (String name : list) {
System.out.println(name);
}
}
}

Kết quả

sampleCollection3
sampleCollection2
sampleCollection4
sampleCollection1