
如果我们直接将 cube 类型的对象存储到 mongodb 中,会得到类似如下的文档结构:
{
"Square": {
"Length": 2,
"Width": 3
},
"Depth": 4
}但我们希望得到如下的扁平化结构:
{
"Length": 2,
"Width": 3,
"Depth": 4
}为了实现这个目标,我们可以使用 bson:",inline" 标签。这个标签告诉 mgo,将嵌套结构体的字段直接嵌入到父级结构体中。
修改后的结构体定义如下:
type Square struct {
Length int `bson:"Length"`
Width int `bson:"Width"`
}
type Cube struct {
Square `bson:",inline"`
Depth int `bson:"Depth"`
}代码示例:
package main
import (
"fmt"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Square struct {
Length int `bson:"Length"`
Width int `bson:"Width"`
}
type Cube struct {
Square `bson:",inline"`
Depth int `bson:"Depth"`
}
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("cubes")
err = c.DropCollection()
if err != nil && err.Error() != "ns not found" {
log.Fatal("Error dropping collection:", err)
}
cube := Cube{
Square: Square{
Length: 2,
Width: 3,
},
Depth: 4,
}
err = c.Insert(&cube)
if err != nil {
log.Fatal(err)
}
result := Cube{}
err = c.Find(bson.M{"Depth": 4}).One(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result) // Output: {{2 3} 4}
// Check the document in MongoDB
// You should see: { "_id" : ObjectId("..."), "Length" : 2, "Width" : 3, "Depth" : 4 }
}注意事项:
总结:
通过使用 bson:",inline" 标签,我们可以方便地将嵌套结构体的字段提升到父级结构体中,从而简化 MongoDB 中的数据结构。这在处理复杂的数据模型时非常有用,可以提高代码的可读性和可维护性。 在使用该标签时,请注意字段名称冲突和 mgo 版本兼容性等问题。
以上就是使用 mgo 存储嵌套结构体的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号