文档菜单
文档首页
/ / /
Go 驱动程序
/ /

插入多个文档

您可以通过使用InsertMany() 方法将多个文档插入到集合中。

提示

阅读使用示例了解如何运行此示例。

此示例使用以下 Restaurant 结构体作为 restaurants 集合中文档的模型

type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Cuisine string `bson:"cuisine,omitempty"`
Address interface{} `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []interface{} `bson:"grades,omitempty"`
}

omitempty 结构化标签在字段为空时省略相应的字段。

以下示例将两个新文档插入到 restaurants 集合中

提示

不存在的数据库和集合

当您执行写入操作时,如果所需的数据库和集合不存在,服务器将隐式创建它们。

coll := client.Database("sample_restaurants").Collection("restaurants")
// Creates two sample documents describing restaurants
newRestaurants := []interface{}{
Restaurant{Name: "Rule of Thirds", Cuisine: "Japanese"},
Restaurant{Name: "Madame Vo", Cuisine: "Vietnamese"},
}
// Inserts sample documents into the collection
result, err := coll.InsertMany(context.TODO(), newRestaurants)
if err != nil {
panic(err)
}

查看可运行的完整示例

运行完整示例后,您可以在 restaurants 集合中找到以下插入的文档

{ "_id": ObjectID("..."), "name": "Rule of Thirds", "cuisine": "Japanese"},
{ "_id": ObjectID("..."), "name": "Madame Vo", "cuisine": "Vietnamese"}

关于如何查找多个文档的示例,请参阅查找多个文档的使用示例。

了解更多关于插入文档的信息,请参阅插入文档。

InsertMany()

返回

插入一个