如何将值添加到bson.D对象 [英] How to add values to an bson.D object
本文介绍了如何将值添加到bson.D对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用golang和MongoDB驱动程序,我想根据从外部获得的数据来修补我的对象之一:
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:
我有一个结构:
type Pivot struct {
Email string `json:"email"`
Base string `json:"base"`
}
和补丁(使用MongoDB更新)
And the patch (with MongoDB Update)
setMap := bson.D{
{"$set", setElements},
}
res, err := collection.UpdateMany(
ctx,
filter,
setMap,
)
我想让setObject有点动态:
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?
推荐答案
附加DocElem (mgo)或 E (go(.mongodb.org)切片,具体取决于您使用的客户端.
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},
}
用bson.DocElem替换bson.E为mgo.
Replace bson.E with bson.DocElem for mgo.
这篇关于如何将值添加到bson.D对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文