对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

插入文档示例

您可以使用InsertOne()方法将文档插入到集合中。

提示

参阅“使用示例”,了解如何运行此示例。

此示例使用以下 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")newRestaurant := Restaurant{Name: "8282", Cuisine: "Korean"} result, err := coll.InsertOne(context.TODO(), newRestaurant)if err != nil { panic(err)}

查看完全可运行的示例

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

{ "_id": ObjectId("..."), "name": "8282", "cuisine": "Korean"}

有关如何查找文档的示例,请参阅查找文档用法示例。

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

InsertOne()

给本页内容打分