Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序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 的使用方法

← 运行命令