Overview
在本指南中,您可以学习如何使用批量操作。
批量操作执行大量写操作。批量操作无需每次操作都调用数据库,只需调用数据库一次即可执行多个操作。
样本数据
本部分的示例使用以下 Book 结构作为 books 集合中文档的模型:
type Book struct { Title string Author string Length int32 }
要运行本部分中的示例,请使用以下代码段将样本数据加载到 db.books 集合中:
coll := client.Database("db").Collection("books") docs := []interface{}{ Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331}, Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103}, } result, err := coll.InsertMany(context.TODO(), docs)
每个文档都包含书籍说明,其中包含与每个文档中的 title(名称)、author(作者)和 length(长度)字段对应的名称、作者和页面长度。
提示
不存在的数据库和集合
如果执行写操作时不存在必要的数据库和集合,服务器会隐式创建这些数据库和集合。
批量写入
要执行批量操作,请将 WriteModel文档大量传递给BulkWrite()方法。
修改行为
BulkWrite() 方法可以选择采用 BulkWriteOptions 类型,该类型表示可用于修改其行为的选项。如果不指定 BulkWriteOptions,则驱动程序将使用每个选项的默认值。
BulkWriteOptions 类型允许您使用以下方法配置选项:
方法 | 说明 |
|---|---|
| Whether to allow the write to opt-out of document level validation. Default: false |
| Whether to stop performing write operations after an error occurs. Default: true |
Return Values
如果批量操作成功,则 BulkWrite() 方法返回 BulkWriteResult 类型,其中包含批量操作的相关信息。BulkWriteResult 类型包含以下属性:
操作
WriteModel 表示一个插入、替换、更新或删除操作。
Insert
要执行插入操作,请创建 InsertOneModel,以指定要插入的文档。要插入多个文档,请为要插入的每个文档创建 InsertOneModel。
InsertOneModel 允许使用以下方法指定其行为:
方法 | 说明 |
|---|---|
| The document to insert. |
例子
以下示例会创建两个 InsertOneModel 实例以插入两个文档:
models := []mongo.WriteModel{ mongo.NewInsertOneModel().SetDocument(Book{Title: "Beloved", Author: "Toni Morrison", Length: 324}), mongo.NewInsertOneModel().SetDocument(Book{Title: "Outline", Author: "Rachel Cusk", Length: 258}), }
替换
要执行替换操作,请创建 ReplaceOneModel,指定待替换文档和替换文档。要替换多个文档,请为每个待替换文档创建一个 ReplaceOneModel。
ReplaceOneModel 允许使用以下方法指定它的行为:
方法 | 说明 |
|---|---|
| The type of language collation to use when sorting results. |
| The query filter specifying which document to replace. |
| The index to use to scan for documents. |
| The document to replace the matched document with. |
| Whether to insert a new document if the query filter doesn't match any documents. |
例子
以下示例创建 ReplaceOneModel,以将 title 为“Lucy”的文档替换为新文档:
models := []mongo.WriteModel{ mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "Lucy"}}). SetReplacement(Book{Title: "On Beauty", Author: "Zadie Smith", Length: 473}), }
Update
要执行更新操作,请创建一个指定要更新文档的 UpdateOneModel 和更新文档。要更新多个文档,请使用 UpdateManyModel。
UpdateOneModel 和 UpdateManyModel 允许您使用以下方法指定它们的行为:
方法 | 说明 |
|---|---|
| The array elements the update applies to. |
| The type of language collation to use when sorting results. |
| The query filter specifying which document to update. |
| The index to use to scan for documents. |
| The modifications to apply on the matched documents. |
| Whether to insert a new document if the query filter doesn't match any documents. |
例子
如果 author(作者)是“Elena Ferrante”,如下示例将创建一个 UpdateOneModel,以便将一个文档的 length(长度)递减 15:
models := []mongo.WriteModel{ mongo.NewUpdateOneModel().SetFilter(bson.D{{"author", "Elena Ferrante"}}). SetUpdate(bson.D{{"$inc", bson.D{{"length", -15}}}}), }
删除
要执行删除操作,请创建一个 DeleteOneModel,以指定要删除的文档。要删除多个文档,请使用 DeleteManyModel。
DeleteOneModel 和 DeleteManyModel 允许您使用以下方法指定它们的行为:
方法 | 说明 |
|---|---|
| The type of language collation to use when sorting results. |
| The query filter specifying which document to delete. |
| The index to use to scan for documents. |
例子
以下示例创建了一个 DeleteManyModel,用于删除 length 大于 300 的文档:
models := []mongo.WriteModel{ mongo.NewDeleteManyModel().SetFilter(bson.D{{"length", bson.D{{"$gt", 300}}}}), }
执行顺序
BulkWrite() 方法支持您在 BulkWriteOptions 中指定以有序方式还是无序方式执行批量操作。
已排序
默认情况下,BulkWrite() 方法按照您添加的顺序执行批量操作,并在出现错误时停止执行。
提示
这相当于在 SetOrdered() 方法中指定 true:
opts := options.BulkWrite().SetOrdered(true)
无序
要按任意顺序执行批量写入操作并在发生错误时继续,请为 SetOrdered()方法指定 false。随后,此方法将报告错误。
例子
以下示例按任意顺序执行以下动作:
插入两个文档。
将
title为“My Brilliant Friend”的文档替换为新文档。如果当前的
length(长度)值小于200,则将每个文档的length(长度)值递增10。删除
author字段值包含“Jam”的所有文档。
models := []mongo.WriteModel{ mongo.NewInsertOneModel().SetDocument(Book{Title: "Middlemarch", Author: "George Eliot", Length: 904}), mongo.NewInsertOneModel().SetDocument(Book{Title: "Pale Fire", Author: "Vladimir Nabokov", Length: 246}), mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "My Brilliant Friend"}}). SetReplacement(Book{Title: "Atonement", Author: "Ian McEwan", Length: 351}), mongo.NewUpdateManyModel().SetFilter(bson.D{{"length", bson.D{{"$lt", 200}}}}). SetUpdate(bson.D{{"$inc", bson.D{{"length", 10}}}}), mongo.NewDeleteManyModel().SetFilter(bson.D{{"author", bson.D{{"$regex", "Jam"}}}}), } opts := options.BulkWrite().SetOrdered(false) results, err := coll.BulkWrite(context.TODO(), models, opts) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", results.InsertedCount) fmt.Printf("Number of documents replaced or updated: %d\n", results.ModifiedCount) fmt.Printf("Number of documents deleted: %d\n", results.DeletedCount)
Number of documents inserted: 2 Number of documents replaced or updated: 2 Number of documents deleted: 1
批量操作后,books(图书)集合中存在以下文档:
{"title":"Atonement","author":"Ian McEwan","length":351} {"title":"Middlemarch","author":"George Eliot","length":904} {"title":"Pale Fire","author":"Vladimir Nabokov","length":246}
更多信息
要了解有关执行上述操作的更多信息,请参阅以下指南:
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: