普通网友 2019-03-22 19:30
浏览 830
已采纳

如何将值添加到bson.D对象

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条回答 默认 最新

  • dongyishe6689 2019-03-22 20:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败