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

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

报告相同问题?

悬赏问题

  • ¥20 c语言写的8051单片机存储器mt29的模块程序
  • ¥60 求直线方程 使平面上n个点在直线同侧并且距离总和最小
  • ¥50 java算法,给定试题的难度数量(简单,普通,困难),和试题类型数量(单选,多选,判断),以及题库中各种类型的题有多少道,求能否随机抽题。
  • ¥50 rk3588板端推理
  • ¥250 opencv怎么去掉 数字0中间的斜杠。
  • ¥15 这种情况的伯德图和奈奎斯特曲线怎么分析?
  • ¥250 paddleocr带斜线的0很容易识别成9
  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大