컬렉션 표시를 사용하여 데이터베이스의 모든 기존 컬렉션 목록을 인쇄할 수 있습니다.
예시
아래와 같이 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에서는 listCollectionNames()를 사용하여 현재 데이터베이스의 모든 컬렉션 이름을 가져올 수 있습니다. com.mongodb.client.MongoCollection인터페이스의 메소드
따라서 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