Overview
在本指南中,您可以了解如何将文档插入到 MongoDB 集合。
在 MongoDB 中查找、更新和删除文档之前,必须先插入这些文档。您可以使用 InsertOne() 方法插入一个文档,也可以使用 InsertMany() 或 BulkWrite() 方法插入多个文档。
以下各部分重点介绍 InsertOne() 和 InsertMany()。要了解如何使用 BulkWrite() 方法,请参阅批量操作指南。
字段 _id
在 MongoDB 中,每个文档都必须包含一个唯一的 _id 字段。
管理这个字段的两个选项是:
自行管理此字段,确保使用的每个值都是唯一的。
让驱动程序自动生成唯一的
ObjectId值。驱动程序会为您未明确指定_id的文档生成唯一的ObjectId值。
除非为唯一性提供强有力的保证,否则,MongoDB 建议让驱动程序自动生成 _id 值。
注意
重复的 _id 值违反了唯一索引约束,导致驱动程序返回 WriteError。
如要了解有关 _id 字段的更多信息,请参阅有关唯一索引的 Server 手册条目。
要了解有关文档结构和规则的更多信息,请参阅服务器手册中有关文档的条目。
插入文档
使用 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)修改 InsertOne 行为
您可以通过构造和传递可选InsertOneOptions结构来修改 InsertOne() 的行为。使用InsertOneOptions设置的可用选项有:
选项 | 说明 |
|---|---|
| 如果为 默认: |
构造一个InsertOneOptions,如下所示:
opts := options.InsertOne().SetBypassDocumentValidation(true)插入多个文档
使用 InsertMany() 方法向集合插入多个文档。
插入成功后,InsertMany() 方法会返回一个 InsertManyResult 实例,其中包含已插入文档的 _id 字段。
例子
下面的示例使用 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: 3Inserted document with _id: ObjectID("...")Inserted document with _id: ObjectID("...")Inserted document with _id: ObjectID("...")修改 InsertMany 行为
您可以通过构造和传递可选InsertManyOptions结构来修改 InsertMany() 的行为。使用InsertManyOptions设置的可用选项有:
选项 | 说明 |
|---|---|
| 如果为 默认: |
| 如果为 默认: |
构造一个InsertManyOptions,如下所示:
opts := options.InsertMany().SetBypassDocumentValidation(true).SetOrdered(false)Ordered 行为
假设要插入以下文档:
{ "_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)}运行上述代码后,您的集合将包含以下文档:
{ "_id": 1, "title": "Where the Wild Things Are" }{ "_id": 2, "title": "The Very Hungry Caterpillar" }更多信息
有关插入操作的可运行示例,请参阅以下使用示例:
要了解有关执行上述操作的更多信息,请参阅以下指南:
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: