7

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?

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It took me a while to check that bson.D is an abson.E array, I had declared as setElements := []bson.E{}
Is this the last resort? I have lots of fields in my database so any better approach?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.