duandoucou7200
2018-10-24 22:05
浏览 67

如何使用mongo-go-driver从结构转换为文档

I'm trying to use $push to put a go struct into a mongo array. The go documents, which I've simplified for this example, look like this:

type Main struct {
   ID       objectid.ObjectID `bson:"_id"`
   Projects []*Project        `bson:"proj"`
}

type Project struct {
   ID    objectid.ObjectID `bson:"_id"`
   Name  string            `bson:"name"`
}

What I want to do is $push a new Project onto the Main.Projects array. What I've ended up doing is quite painful, so I'm hoping there is a better way. See here:

// 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 ...

Is it really necessary to transcode to a byte buffer, then read into a document? I was hoping for something like:

...
bson.EC.GoStruct("proj", newProj)
...

I did try bson.EC.Interface("proj", newProj) but that just inserted nulls into the array. I am curious to know how others are doing this sort of thing.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhao5656 2018-10-25 04:42
    已采纳

    You are right, there is a simpler way to go about this:

    newProj := &Project{
        ID: objectid.New(),
        Name: "foo",
    }
    
    upd := bson.M{
        "$push": bson.M{"proj": newProj},
    }
    

    I'm using github.com/globalsign/mgo/bson

    点赞 打赏 评论

相关推荐 更多相似问题