Docs 菜单
Docs 主页
/ / /
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")
newRestaurants := []interface{}{
Restaurant{Name: "Rule of Thirds", Cuisine: "Japanese"},
Restaurant{Name: "Madame Vo", Cuisine: "Vietnamese"},
}
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()

后退

插入文档