如何将bson.M元素列表合并到golang中的mongo中的单个bson.M中?

时间:2016-02-15 08:45:55

标签: mongodb go bson mgo

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}}

需要追加相同密钥的所有操作。提前谢谢

1 个答案:

答案 0 :(得分:0)

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
}

这是你可以尝试的