hestellezg
hestellezg

Reputation: 3711

How to add values to an bson.D object

I'm working with golang and the MongoDB driver, I want to patch one of my objects according to the data I get from the outside:

I have a struct:

type Pivot struct {
    Email        string             `json:"email"`
    Base         string             `json:"base"`
}

And the patch (with MongoDB Update)

setMap := bson.D{
        {"$set", setElements},
    }

res, err := collection.UpdateMany(
    ctx,
    filter,
    setMap,
)

And I want to make the setObject a little bit dynamic:

if len(pivot.Base) > 0 {
  setElements.append("base", pivot.Base) //this doesn't work...
}
if len(pivot.Email) > 0 {
  setElements.append("email", pivot.Email)
}

I' ve seen that the setObject can be built like

{"$set", bson.D{
    {"processed", pivot.Processed},
}

But how can I make it dynamic?

Upvotes: 7

Views: 14979

Answers (1)

Thundercat
Thundercat

Reputation: 120931

Append a DocElem (mgo) or an E (go.mongodb.org) to the slice depending on the client you are using.

var setElements bson.D
if len(pivot.Base) > 0 {
  setElements = append(setElements, bson.E{"base", pivot.Base})
}
if len(pivot.Email) > 0 {
    setElements = append(setElements, bson.E{"email", pivot.Email})
}

setMap := bson.D{
    {"$set", setElements},
}

Replace bson.E with bson.DocElem for mgo.

Upvotes: 17

Related Questions