drop()을 사용하여 MongoDB에서 기존 컬렉션을 삭제할 수 있습니다. 방법.
구문
db.coll.drop()
어디,
-
DB 데이터베이스입니다.
-
콜 문서를 삽입할 컬렉션(이름)입니다.
예시
아래와 같이 MongoDB 데이터베이스에 3개의 컬렉션을 생성했다고 가정합니다. -
> use sampleDatabase
switched to db sampleDatabase
> db.createCollection("students")
{ "ok" : 1 }
> db.createCollection("teachers")
{ "ok" : 1 }
> db.createCollection("sample")
{ "ok" : 1 }
> show collections
sample
students
teachers 다음 쿼리는 sample이라는 컬렉션을 삭제합니다.
> db.sample.drop() true > show collections example students teachers
자바 프로그램 사용
자바에서는 drop()을 사용하여 현재 컬렉션에서 컬렉션을 삭제할 수 있습니다. 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()를 사용하여 데이터베이스에 연결 방법.
-
getCollection()을 사용하여 삭제하려는 컬렉션의 개체를 가져옵니다. 방법.
-
drop() 메서드를 호출하여 컬렉션을 삭제합니다.
예시
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;
public class DropingCollection {
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();
System.out.println("List of collections:");
for (String name : list) {
System.out.println(name);
}
database.getCollection("sampleCollection4").drop();
System.out.println("Collection dropped successfully");
System.out.println("List of collections after the delete operation:");
for (String name : list) {
System.out.println(name);
}
}
} 출력
List of collections: sampleCollection4 sampleCollection1 sampleCollection3 sampleCollection2 Collection dropped successfully List of collections after the delete operation: sampleCollection1 sampleCollection3 sampleCollection2