duandoucou7200 2018-10-24 22:05
浏览 69
已采纳

如何使用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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误