普通网友 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.

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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元