dsapkqaduj6718493 2016-02-15 08:45 采纳率: 100%
浏览 938
已采纳

如何在golang中的mongo中将bson.M元素列表组合成单个bson.M?

lstMap := make([]interface{}, 0)
lstMap = mongoOps.AddToBsonMap(lstMap, bson.M{"$inc": bson.M{"Google.ab.Value": 1}})
lstMap = mongoOps.AddToBsonMap(lstMap, bson.M{"$inc": bson.M{"Google.ab1.Value1": 1}})

func (o *MongoOps) AddToBsonMap(lstMap []interface{}, value interface{}) (result []interface{}) {
lstMap = append(lstMap, value)
return lstMap

}

 I want the in this format :
 bson.M{"$inc": bson.M{"Google.ab.Value": 1, "AB.Value.to": 2}}

All the operation of same key needs to be appended.Thank you in advance

  • 写回答

2条回答 默认 最新

  • douteng5673 2016-02-24 12:36
    关注
    func (o *MongoOps) AddToBsonMapElement(lstMap map[string]interface{},     Operation string, key string, value interface{}) (result map[string]interface{})     {
    status, msg := EmptyStructCheck(o)
    if status == true {
        LogError(msg)
        panic(msg)
    }
    if Operation == "$addToSetEach" {
        if _, ok := lstMap["$addToSet"]; ok {
            childmap := lstMap["$addToSet"]
            subchildmap := childmap.(map[string]interface{})
            var val map[string]interface{}
            val = make(map[string]interface{})
            val["$each"] = value
            subchildmap[key] = val
            lstMap["$addToSet"] = subchildmap
    
        } else {
            lstMap["$addToSet"] = bson.M{key: bson.M{"$each": value}}
        }
    
        fmt.Println(reflect.TypeOf(lstMap))
    } else if _, ok := lstMap[Operation]; ok {
        childmap := lstMap[Operation]
        subchildmap := childmap.(map[string]interface{})
        subchildmap[key] = value
        lstMap[Operation] = subchildmap
    
    } else {
        childmap := make(map[string]interface{}, 0)
        childmap[key] = value
        lstMap[Operation] = childmap
    }
    
    return lstMap
    }
    

    This is what you can try

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?