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

如何在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条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格