Docs 菜单
Docs 主页
/ / /
Go
/ / /

插入文档

在此页面上

  • 概述
  • _id 字段
  • 插入文档
  • 例子
  • 修改 InsertOne 行为
  • 插入多个文档
  • 例子
  • 修改 InsertMany 行为
  • Ordered 行为
  • 更多信息
  • API 文档

在本指南中,您可以了解如何将文档插入到 MongoDB 集合。

在 MongoDB 中查找、更新和删除文档之前,您需要先插入这些文档。 您可以使用 InsertOne()方法插入一个文档,也可以使用InsertMany()BulkWrite()方法插入多个文档。

以下部分重点介绍InsertOne()InsertMany() 。要了解如何使用BulkWrite()方法,请参阅批量操作指南。

在 MongoDB 中,每个文档都必须包含一个唯一的 _id 字段。

管理这个字段的两个选项是:

  • 自行管理此字段,确保使用的每个值都是唯一的。

  • 让驱动程序自动生成唯一的 ObjectId 值。驱动程序会为您未明确指定 _id 的文档生成唯一的 ObjectId 值。

除非为唯一性提供强有力的保证,否则,MongoDB 建议让驱动程序自动生成 _id 值。

注意

重复的 _id 值违反了唯一索引约束,导致驱动程序返回 WriteError

要了解有关_id字段的更多信息,请参阅有关唯一索引的服务器手册条目。

要了解有关文档结构和规则的更多信息,请参阅服务器手册中有关文档的条目。

使用 InsertOne() 方法向集合插入多个文档。

成功插入后,该方法将返回一个包含新文档 _idInsertOneResult 实例。

此示例使用以下 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)

您可以通过构造和传递可选InsertOneOptions结构来修改 InsertOne() 的行为。使用InsertOneOptions设置的可用选项有:

选项
说明
BypassDocumentValidation
If true, allows the write to opt-out of document level validation.
Default: false

构造一个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: 3
Inserted document with _id: ObjectID("...")
Inserted document with _id: ObjectID("...")
Inserted document with _id: ObjectID("...")

您可以通过构造和传递可选InsertManyOptions结构来修改 InsertMany() 的行为。使用InsertManyOptions设置的可用选项有:

选项
说明
BypassDocumentValidation
If true, allows the write to opt-out of document level validation.
Default: false
Ordered
If true, the driver sends documents to the server in the order provided. If an error occurs, the driver and server end all remaining insert operations. To learn more, see Ordered Behavior.
Default: 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)
}

当查看集合内部时,您应当能够看到以下文档:

{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }

有关插入操作的可运行示例,请参阅以下使用示例:

要了解有关执行上述操作的更多信息,请参阅以下指南:

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

写入操作