文档菜单
文档首页
/ / /
Java 同步驱动程序
/ /

删除文档

您可以使用以下方法从集合中删除单个文档:MongoCollection 对象上使用 deleteOne() 方法。该方法接受一个查询过滤器,该过滤器与您想要删除的文档相匹配。如果您不指定过滤器,MongoDB 将匹配集合中的第一个文档。deleteOne() 方法仅删除匹配的第一个文档。

此方法返回一个 DeleteResult 实例,其中包含有关操作结果删除了多少文档的信息。

如果您的删除操作失败,驱动程序将抛出异常。有关在特定条件下引发的异常类型的更多信息,请参阅此页底部链接的 deleteOne() API 文档。

以下代码片段从 sample_mflix 数据库的 movies 集合中删除单个文档。该示例使用 eq() 过滤器来匹配标题完全匹配文本 'The Garbage Pail Kids Movie' 的电影。

注意

此示例使用连接 URI 连接到 MongoDB 实例。有关连接到您的 MongoDB 实例的更多信息,请参阅连接指南.

// Deletes a document from a collection by using the Java driver
package usage.examples;
import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
public class DeleteOne {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Bson query = eq("title", "The Garbage Pail Kids Movie");
try {
// Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie"
DeleteResult result = collection.deleteOne(query);
System.out.println("Deleted document count: " + result.getDeletedCount());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to delete due to an error: " + me);
}
}
}
}

当您运行示例时,如果您传递给 deleteOne() 的查询过滤器与您的集合中的文档匹配并删除了它,您应该看到类似以下输出的结果

Deleted document count: 1

如果您的查询过滤器与您的集合中的文档不匹配,您的 deleteOne() 调用不会删除任何文档并返回以下内容

Deleted document count: 0

提示

旧版 API

如果您正在使用旧版 API,请参阅我们的常见问题解答页面,了解您需要对此代码示例进行哪些更改。

有关本页提到的类和方法的更多信息,请参阅以下 API 文档

  • deleteOne()

  • DeleteResult

  • eq()

返回

删除