Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Go 驱动程序
/

使用结构体标记

可以使用结构标签指定 Go 驱动程序将 Go 结构转换为 BSON 的方式。

注意

设置示例

此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 sample_restaurants数据库中的 restaurants集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。

此示例使用以下结构体标签声明类型为 Restaurant 的结构体:

  • 一个结构体标签,用于将 RestaurantId字段映射到BSON字段名称 restaurant_id。默认下,驾驶员会将其他字段编组为结构字段名称的小写形式。

  • omitempty 结构体标签留空时会省略插入文档中的相应字段。

以下代码显示了示例中使用的 Restaurant 结构:

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"`
}

以下示例创建一个 Restaurant实例并将其插入到 restaurants集合中。在插入操作过程中,驾驶员会解释结构体标签,将 RestaurantId 结构体字段封送为 restaurant_id,并省略示例文档中留空的字段:

// Specifies struct tags on a struct by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Specifies a different name for RestaurantID
// and marks certain fields as omitempty
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"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/usage-examples/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
// Creates a Restaurant document
newRestaurant := Restaurant{
Name: "Amazing Pizza",
RestaurantId: "123456789",
Cuisine: "American",
}
// Inserts the sample document describing a restaurant into the collection
result, err := coll.InsertOne(context.TODO(), newRestaurant)
if err != nil {
panic(err)
}
// Prints the ID of the inserted document
fmt.Printf("Document inserted with ID: %s\n", result.InsertedID)
// When you run this file, it should print:
// Document inserted with ID: ObjectID("...")
}
Document inserted with ID: ObjectID("...")

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

{
"_id" : ObjectId("..."),
"name" : "Amazing Pizza",
"restaurant_id" : "123456789",
"cuisine" : "American
}

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

要学习;了解有关使用结构体标签、与BSON相互转换以及处理潜在错误的更多信息,请参阅 使用BSON指南

后退

Data Formats