Overview
在本指南中,您可以了解如何使用删除操作从 MongoDB 集合中删除文档。
样本数据
本指南中的示例将以下 Book
结构作为 books
集合中的文档的模型:
type Book struct { Title string Author string Length int32 }
要运行本指南中的示例,请使用以下代码段将样本数据加载到 db.books
集合中:
coll := client.Database("db").Collection("books") docs := []interface{}{ Book{Title: "Atonement", Author: "Ian McEwan", Length: 351}, Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331}, Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103}, Book{Title: "Outline", Author: "Rachel Cusk", Length: 258}, } result, err := coll.InsertMany(context.TODO(), docs)
每个文档都包含书籍说明,其中包含与每个文档中的 title
(名称)、author
(作者)和 length
(长度)字段对应的名称、作者和页面长度。
提示
不存在的数据库和集合
如果执行写操作时不存在必要的数据库和集合,服务器会隐式创建这些数据库和集合。
删除操作
使用删除操作从 MongoDB 中删除数据。删除操作由以下方法组成:
DeleteOne()
,会删除与筛选器匹配的第一个文档DeleteMany()
,删除所有符合筛选条件的文档
提示
如果运行 DeleteMany()
方法时有一个文档与您的筛选器匹配,则相当于运行 DeleteOne()
方法。
参数
DeleteOne()
和 DeleteMany()
方法需要您传递 Context
类型和 non-nil
查询筛选器,以指定要匹配的文档。
它们都可以选择性地采用 DeleteOptions
类型作为第三个参数,该参数表示可用于配置删除操作的选项。如果不指定 DeleteOptions
,驱动程序将使用各选项的默认值。
DeleteOptions
类型允许您使用以下方法配置选项:
方法 | 说明 |
---|---|
| The index to use to scan for documents to delete. Default: nil |
| The type of language collation to use when sorting results. Default: nil |
返回值
DeleteOne()
和 DeleteMany()
方法返回 DeleteResult
类型。该类型包含 DeletedCount
属性,其中说明了已删除文档的数量。如果筛选器中没有匹配项,则不会删除任何文档,DeletedCount
为 0
。
例子
以下示例使用 DeleteMany()
方法执行以下操作:
匹配并删除
length
(长度)大于300
的文档指示此方法使用
_id
作为索引
filter := bson.D{{"length", bson.D{{"$gt", 300}}}} opts := options.Delete().SetHint(bson.D{{"_id", 1}}) result, err := coll.DeleteMany(context.TODO(), filter, opts) if err != nil { panic(err) } fmt.Printf("Number of documents deleted: %d\n", result.DeletedCount)
Number of documents deleted: 2
提示
如果上述示例中使用的是 DeleteOne()
方法而不是 DeleteMany()
,驱动程序将删除两个匹配文档中的第一个。
DeleteOne() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用 Atlas示例数据集包含的 sample_restaurants
数据库中的 restaurants
集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下示例是一个完全可运行的文件,用于查找并删除 restaurants
集合中的现有文档。
// Deletes a document from a collection by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines a Restaurant struct as a model for documents in the "restaurants" collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string `bson:"name"` Cuisine string `bson:"cuisine,omitempty"` Address interface{} `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []interface{} `bson:"grades,omitempty"` } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"name", "New Corner"}} // Deletes the first document that has a "name" value of "New Corner" result, err := coll.DeleteOne(context.TODO(), filter) // Prints a message if any errors occur during the operation if err != nil { panic(err) } // Prints the number of deleted documents fmt.Printf("Documents deleted: %d\n", result.DeletedCount) // When you run this file for the first time, it prints output similar to the following: // Documents deleted: 1 }
Documents deleted: 1
DeleteMany() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 sample_restaurants
数据库中的 restaurants
集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下示例是一个完全可运行的文件,它对 restaurants
集合执行以下操作:
匹配并删除
cuisine
字段值为German
且borough
字段值为Queens
的文档删除所有匹配的文档
// Deletes multiple documents from a collection by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines a Restaurant struct as a model for documents in the "restaurants" collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string `bson:"name"` Borough string `bson:"borough"` Cuisine string `bson:"cuisine"` } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{ {"borough", "Queens"}, {"cuisine", "German"}, } // Deletes all documents that have a "Borough" value of "Queens" and a "Cuisine" value of "German" results, err := coll.DeleteMany(context.TODO(), filter) if err != nil { panic(err) } // Prints the number of deleted documents fmt.Printf("Documents deleted: %d\n", results.DeletedCount) // When you run this file for the first time, it prints output similar to the following: // Documents deleted: 6 }
Documents deleted: 6
更多信息
要了解有关执行上述操作的更多信息,请参阅以下指南:
要学习;了解驾驶员如何使用 Context,请参阅 Context 包。
要详细了解如何指定提示,请参阅索引。
要学习;了解有关排序规则的更多信息,请参阅 golang-collations.
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: