dqhr76378 2015-12-02 00:32
浏览 10
已采纳

如何基于输入创建bson映射

I am building a bson map in golang using mgo library. I want to refactor some code to be able to avoid duplication.

Consider this:

    bson.M {
         "$match" : bson.M{
            "xyz" : "abc",
          },
          "$id_1" : value_1, 
    }

and another bson map of type:

    bson.M {
         "$match" : bson.M{
            "xyz" : "abc",
          },
          "$id_2" : value_2,
    }

How can I combine the two (build bson.M from a function and return, value1/2 are params to this func) to be used based on if value_1 is empty string or value_2 is empty string.

For example: if I build a the following function. My intention is to build map of first type (see above) by calling buildBsonObject("123","") and the second one by calling buildBsonObject("", "456").

func buildBsonObject (value_1 string, value_2 string) {    
    return bson.M {
             "$match" : bson.M{
                "xyz" : "abc",
              },
              "$id_1" : value_1, 
              "$id_2" : value_2,
        }
}

If I do the following (see function buildBsonObject), then when value_1 is empty string, my mongo aggregation query will not work since it will treat as id_1 being "", whereas I intended to just have id_2 in my bson object.

Any suggestions on how to do this. Thanks.

  • 写回答

1条回答 默认 最新

  • du1108 2015-12-02 01:17
    关注

    How about this:

    func buildBsonObject(value_1 string, value_2 string) bson.M {
      m := bson.M{
        "$match": bson.M{
            "xyz": "abc",
        },
      }
      if value_1 != "" {
        m["$id_1"] = value_1
      }
      if value_2 != "" {
        m["$id_2"] = value_2
      }
      return m
    }
    

    playground example

    An alternative is to pass the key name to the function:

    func buildBsonObject(k string, v string) bson.M {
      return bson.M{
        "$match": bson.M{
            "xyz": "abc",
        },
        k: v,
      }
    }
    

    playground example

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP