删除文档
您可以通过使用以下方法在集合中删除文档:DeleteOne()
方法。
示例
提示
阅读使用示例 了解如何运行此示例。
以下示例匹配 movies
集合中标题为 "Twilight" 的文档,删除第一个匹配的文档
coll := client.Database("sample_mflix").Collection("movies") filter := bson.D{{"title", "Twilight"}} // Deletes the first document that has a "title" value of "Twilight" result, err := coll.DeleteOne(context.TODO(), filter) // Prints a message if any errors occur during the operation if err != nil { panic(err) }
查看一个可运行的完整示例。
预期结果
运行完整示例后,它将删除 movies
集合中的以下文档
// result truncated { "_id": ObjectId("..."), ..., "title": "Twilight", ... }
有关查找文档的示例,请参阅 查找文档。
更多信息
要了解有关删除文档的更多信息,请参阅 删除文档。