Java Mongodb 简明教程

Java & MongoDB - Delete Document

若要删除一个集合中的文档,可以使用 collection.deleteOne() 方法删除一个集合中的特定文档。

collection.deleteOne(filter);

Example

以下是删除一个文档并显示其余文档的代码片段 −

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find all documents
      collection.deleteOne(Filters.eq("First_Name","Mahesh"));
      System.out.println("Document deleted.");
      System.out.println("***Documents***");

      // Select a particular document
      FindIterable<Document> documents = collection.find();

      for (Document document : documents) {
         System.out.println(document);
      }
   }
}

现在,我们按照以下步骤编译并运行上述程序。

$javac Tester.java
$java Tester

Output

在执行上述程序时,您将得到以下输出。

Document deleted.
***Documents***
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}