자바에서 com.mongodb.client.MongoCollection 인터페이스는 deleteMany() 메서드를 제공합니다. . 이 방법을 사용하면 컬렉션에서 여러 문서를 한 번에 삭제할 수 있으며 이 방법을 사용하려면 삭제 기준을 지정하는 필터를 통과해야 합니다.
예시
import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoClient; public class DeletingMultipleDocuments { public static void main( String args[] ) { //Creating a MongoDB client MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Connecting to the database MongoDatabase database = mongo.getDatabase("myDatabase"); //Creating a collection object MongoCollection<Document>collection = database.getCollection("students"); Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Delhi"); Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam"); Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi"); Document document4 = new Document("name", "Radha").append("age", 45).append("city", "Delhi"); Document document5 = new Document("name", "Sarmista").append("age", 35).append("city", "Mumbai"); //Inserting the created documents List<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); list.add(document3); list.add(document4); list.add(document5); collection.insertMany(list); System.out.println("Documents Inserted"); System.out.println("Contents of the collection:"); FindIterable<Document> iterDoc = collection.find(); int i = 1; System.out.println("Remaining documents:"); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); i++; } collection = database.getCollection("students"); //Deleting multiple documents Bson filter = new Document("city", "Delhi"); collection.deleteMany(filter); System.out.println("Document deleted successfully..."); //Retrieving the documents after the delete operation iterDoc = collection.find(); System.out.println("Remaining documents:"); it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); i++; } } }
출력
Documents Inserted Contents of the collection: Remaining documents: Document{{_id=5e896b042e4a2f3badebddae, name=Ram, age=26, city=Delhi}} Document{{_id=5e896b042e4a2f3badebddaf, name=Robert, age=27, city=Vishakhapatnam}} Document{{_id=5e896b042e4a2f3badebddb0, name=Rhim, age=30, city=Delhi}} Document{{_id=5e896b042e4a2f3badebddb1, name=Radha, age=45, city=Delhi}} Document{{_id=5e896b042e4a2f3badebddb2, name=Sarmista, age=35, city=Mumbai}} Document deleted successfully... Remaining documents: Document{{_id=5e896b042e4a2f3badebddaf, name=Robert, age=27, city=Vishakhapatnam}} Document{{_id=5e896b042e4a2f3badebddb2, name=Sarmista, age=35, city=Mumbai}}