如何使用mongo-go-driver

时间:2018-10-24 22:05:11

标签: mongodb go

我正在尝试使用$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数组上Project新建一个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),但只是将空值插入了数组。我很想知道别人是怎么做这种事情的。

1 个答案:

答案 0 :(得分:0)

您是对的,有一种更简单的方法可以解决此问题:

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

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

我正在使用github.com/globalsign/mgo/bson