如何使用 Java 从集合中删除多个文档?
在 Java 中,com.mongodb.client.MongoCollection 接口提供了一个 deleteMany()方法。使用此方法,您可以一次从集合中删除多个文档,需要向此方法传递指定删除条件的 filter。
示例
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}}
广告