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.