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

使用结构标签

您可以使用结构标签来指定 Go 驱动如何将 Go 结构体转换为BSON

提示

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

以下代码声明了一个类型为BlogPost的结构体。此结构体包含一个结构体标签,将WordCount字段映射到BSON字段名word_count。默认情况下,驱动程序将其他字段序列化为结构体字段名的小写形式

type BlogPost struct {
Title string
Author string
WordCount int `bson:"word_count"`
LastUpdated time.Time
Tags []string
}

以下示例创建了一个BlogPost实例并将其插入到posts集合中。在插入操作期间,驱动程序解释结构体标签将WordCount结构体字段序列化为word_count

提示

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

coll := client.Database("sample_training").Collection("posts")
post := BlogPost{
Title: "Annuals vs. Perennials?",
Author: "Sam Lee",
WordCount: 682,
LastUpdated: time.Now(),
Tags: []string{"seasons", "gardening", "flower"},
}
// Inserts a document describing a blog post into the collection
_, err = coll.InsertOne(context.TODO(), post)
if err != nil {
panic(err)
}

查看一个可运行的示例。

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

{
"_id" : ObjectId("..."),
"title" : "Annuals vs. Perennials?",
"author" : "Sam Lee",
"word_count" : 682,
"lastupdated": ...,
"tags" : ["seasons", "gardening", "flower"]
}

有关查找文档的示例,请参阅 查找文档。

有关使用结构体标签、BSON 转换以及处理潜在错误的更多信息,请参阅 使用 BSON。

返回

运行命令