我正在尝试从一个大量嵌套的go结构构建一个mongo文档,而且我遇到了从go结构转换为mongo对象的问题.我已经构建了一个非常简化的版本,我正在尝试使用它:http://play.golang.org/p/yPZW88deOa
package main
import (
"os"
"fmt"
"encoding/json"
)
type Square struct {
Length int
Width int
}
type Cube struct {
Square
Depth int
}
func main() {
c := new(Cube)
c.Length = 2
c.Width = 3
c.Depth = 4
b, err := json.Marshal(c)
if err != nil {
panic(err)
}
fmt.Println(c)
os.Stdout.Write(b)
}
Run Code Online (Sandbox Code Playgroud)
运行此命令会产生以下输出:
&{{2 3} 4}
{"Length":2,"Width":3,"Depth":4}
Run Code Online (Sandbox Code Playgroud)
这完全有道理.似乎Write函数或json.Marshal函数都有一些功能可以折叠嵌套结构,但是当我尝试使用mgo函数将这些数据插入mongo数据库时,我的问题出现了func (*Collection) Upsert(http://godoc.org/labix .org/v2/mgo#Collection.Upsert).如果我json.Marshal()首先使用该函数并将字节传递给collection.Upsert()它,它将存储为二进制文件,这是我不想要的,但如果我使用collection.Upsert(bson.M("_id": id, &c) …