首页 > 解决方案 > 如何使用 mongo-go-driver 从结构转换为文档

问题描述

我正在尝试$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一个新ProjectMain.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)过,但这只是将空值插入到数组中。我很想知道其他人是如何做这种事情的。

标签: mongodbgo

解决方案


你是对的,有一种更简单的方法可以解决这个问题:

newProj := &Project{
    ID: objectid.New(),
    Name: "foo",
}

upd := bson.M{
    "$push": bson.M{"proj": newProj},
}

我在用着github.com/globalsign/mgo/bson


推荐阅读