简体   繁体   中英

How to convert from a struct to a document with 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM