我正在尝试从高度嵌套的go结构构建mongo文档,并且从go struct过渡到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)
}
运行此命令将产生以下输出:
&{{2 3} 4}
{"Length":2,"Width":3,"Depth":4}
完全有道理。似乎Write函数或json.Marshal函数具有使折叠的struct折叠的功能,但是当我尝试使用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)
它,它将显示为嵌套结构,其形式为:
{
"Square": {
"Length": 2
"Width": 3
}
"Depth": 4
}
但是我想要做的是使用与使用该os.Stdout.Write()
函数时相同的结构来向mongo上插入:
{
"Length":2,
"Width":3,
"Depth":4
}
我是否缺少一些可以轻松解决此问题的标志?在这一点上,我能看到的唯一选择是通过删除结构的嵌套来严重降低代码的可读性,而我真的很讨厌这样做。同样,我的实际代码比本示例要复杂得多,因此,如果我可以避免通过嵌套嵌套而使其更加复杂,那绝对是可取的。
我认为使用inline
字段标签是您的最佳选择。该氧化镁/ V2 / BSON文档状态:
inline Inline the field, which must be a struct or a map,
causing all of its fields or keys to be processed as if
they were part of the outer struct. For maps, keys must
not conflict with the bson keys of other struct fields.
然后,您的结构应定义如下:
type Cube struct {
Square `bson:",inline"`
Depth int
}
编辑
inline
mgo/v1/bson
如果您正在使用那个,也存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句