插入文档
概述
在本指南中,您可以学习如何将文档插入到MongoDB集合中。
在您可以在MongoDB中查找、更新和删除文档之前,您必须先插入这些文档。您可以通过使用InsertOne()
方法插入一个文档,或者通过使用 InsertMany()
或 BulkWrite()
方法插入多个文档。
以下部分重点介绍 InsertOne()
和 InsertMany()
。要了解如何使用 BulkWrite()
方法,请参阅批量操作 指南。
_id
字段
在MongoDB中,每个文档 必须 包含一个唯一的 _id
字段。
管理此字段的两种选项是
自行管理此字段,确保您使用的每个值都是唯一的。
让驱动程序自动生成唯一的
ObjectId
值。驱动程序为未显式指定_id
的文档生成唯一的ObjectId
值。
除非您提供了强大的唯一性保证,否则MongoDB建议您让驱动程序自动生成 _id
值。
注意
重复的 _id
值违反了唯一索引约束,这会导致驱动程序返回一个 WriteError
。
有关 _id
字段的更多信息,请参阅唯一索引.
要了解有关文档结构和规则的更多信息,请参阅文档的服务器手册条目。
插入文档
使用InsertOne()
方法将单个文档插入到集合中。
成功插入后,该方法返回一个包含新文档_id
的InsertOneResult
实例。
示例
以下示例使用以下Book
结构作为books
集合中文档的模型。
type Book struct { Title string Author string }
以下示例使用InsertOne()
方法创建并插入文档到books
集合中。
coll := client.Database("db").Collection("books") doc := Book{Title: "Atonement", Author: "Ian McEwan"} result, err := coll.InsertOne(context.TODO(), doc) fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)
Inserted document with _id: ObjectID("...")
修改InsertOne
行为
您可以通过构造并传递一个可选的 InsertOneOptions
结构来修改 InsertOne()
的行为。可以使用 InsertOneOptions
设置的可用选项有:
选项 | 描述 |
---|---|
BypassDocumentValidation | 如果设置为 true ,允许写操作选择退出 文档级别的验证。默认值: false |
以下是如何构建 InsertOneOptions
:
opts := options.InsertOne().SetBypassDocumentValidation(true)
插入多个文档
使用 InsertMany()
方法将多个文档插入到集合中。
在成功插入后,InsertMany()
方法返回一个包含插入文档的 _id
字段的 InsertManyResult
实例。
示例
以下示例演示了如何使用 InsertMany()
方法创建多个文档并将它们插入到 books
集合中
coll := client.Database("myDB").Collection("favorite_books") docs := []interface{}{ Book{Title: "Cat's Cradle", Author: "Kurt Vonnegut Jr."}, Book{Title: "In Memory of Memory", Author: "Maria Stepanova"}, Book{Title: "Pride and Prejudice", Author: "Jane Austen"}, } result, err := coll.InsertMany(context.TODO(), docs) fmt.Printf("Documents inserted: %v\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("Inserted document with _id: %v\n", id) }
运行上述代码后,您的输出类似于以下内容
Documents inserted: 3 Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...")
修改 InsertMany
行为
您可以通过构造并传递一个可选的 InsertManyOptions
结构来修改 InsertMany()
的行为。可以使用 InsertManyOptions
设置的可用选项有:
选项 | 描述 |
---|---|
BypassDocumentValidation | 如果设置为 true ,允许写操作选择退出 文档级别的验证。默认值: false |
Ordered | 如果 true ,则驱动程序将按提供的顺序将文档发送到服务器。如果发生错误,驱动程序和服务器将终止所有剩余的插入操作。有关更多信息,请参阅有序 行为。默认值: false |
按照以下方式构建一个InsertManyOptions
:
opts := options.InsertMany().SetBypassDocumentValidation(true).SetOrdered(false)
有序
行为
假设您想插入以下文档:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 1, "title": "Blueberries for Sal" } { "_id": 3, "title": "Goodnight Moon" }
如果您使用默认的InsertManyOptions
尝试插入这些文档,由于重复的_id
值,将在第三个文档处发生BulkWriteException
,但错误产生的文档之前的文档仍然被插入到您的集合中。
注意
即使发生BulkWriteException,您也可以获取文档插入成功的确认
type Book struct { ID int `bson:"_id"` Title string } ... docs := []interface{}{ Book{ID: 1, Title: "Where the Wild Things Are"}, Book{ID: 2, Title: "The Very Hungry Caterpillar"}, Book{ID: 1, Title: "Blueberries for Sal"}, Book{ID: 3, Title: "Goodnight Moon"}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { fmt.Printf("A bulk write error occurred, but %v documents were still inserted.\n", len(result.InsertedIDs)) } for _, id := range result.InsertedIDs { fmt.Printf("Inserted document with _id: %v\n", id) }
A bulk write error occurred, but 2 documents were still inserted. Inserted document with _id: 1 Inserted document with _id: 2
运行前面的代码后,您的集合包含以下文档:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" }
附加信息
有关插入操作的运行示例,请参阅以下用法示例
有关执行所提及操作的更多信息,请参阅以下指南
API 文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下 API 文档