我试图使用$push将go结构放入mongo数组中。我为本例简化的go文档如下所示:
type Main struct {
ID objectid.ObjectID `bson:"_id"`
Projects []*Project `bson:"proj"`
}
type Project struct {
ID objectid.ObjectID `bson:"_id"`
Name string `bson:"name"`
}我想要做的是将一个新的$push放到Main.Projects数组上。我最后所做的是相当痛苦的,所以我希望有一个更好的方法。见这里:
// Create the new project struct:
newProj := &Project{
ID: objectid.New(),
Name: "foo",
}
// Then marshall bson:
bsbuf, err := bsoncodec.Marshal(newProj)
if err != nil {
// ...
}
// Next read the bytes into a document:
bsonDoc, err := bson.ReadDocument(bsbuf)
if err != nil {
// ...
}
// Now create the update document:
upd := bson.NewDocument(
bson.EC.SubDocument("$push", bson.NewDocument(
bson.EC.SubDocument("proj", bsonDoc))))
// And perform update as usual
// ... not shown ...是否真的有必要将代码转换为字节缓冲区,然后读取到文档中?我希望有这样的东西:
...
bson.EC.GoStruct("proj", newProj)
...我确实尝试过bson.EC.Interface("proj", newProj),但这只是在数组中插入了空值。我很想知道别人是怎么做这种事的。
发布于 2018-10-25 04:42:50
你说得对,有一种更简单的方法:
newProj := &Project{
ID: objectid.New(),
Name: "foo",
}
upd := bson.M{
"$push": bson.M{"proj": newProj},
}我用的是github.com/globalsign/mgo/bson
https://stackoverflow.com/questions/52978533
复制相似问题