在Java中,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[] ) { //创建一个MongoDB客户端 MongoClient mongo = new MongoClient( "localhost" , 27017 ); //连接到数据库 MongoDatabase database = mongo.getDatabase("myDatabase"); //创建一个收集对象 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"); //插入创建的文档 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("集合的内容:"); FindIterable<Document> iterDoc = collection.find(); int i = 1; System.out.println("剩余文件:"); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); i++; } collection = database.getCollection("students"); //删除多个文档 Bson filter = new Document("city", "Delhi"); collection.deleteMany(filter); System.out.println("Document deleted successfully..."); //删除操作后检索文档 iterDoc = collection.find(); System.out.println("剩余文件:"); it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); i++; } } }
输出结果
Documents Inserted 集合的内容: 剩余文件: 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... 剩余文件: Document{{_id=5e896b042e4a2f3badebddaf, name=Robert, age=27, city=Vishakhapatnam}} Document{{_id=5e896b042e4a2f3badebddb2, name=Sarmista, age=35, city=Mumbai}}