duanliao6789 2014-10-29 12:03
浏览 132
已采纳

使用mgo通过输入选择查询的选定字段

Is it possible to have a method that takes as input an array of strings and then use this array to create the selected fields of a query? So if you have lets say this array:

var myArray []string{"fieldA","fieldB"}

Then you can create this automatically:

selectedFields := bson.M{"fieldA": 1, "fieldB": 1}

and then execute the query

result = c.Find(query).Select(selectedFields).One()
  • 写回答

1条回答 默认 最新

  • duankang5882 2014-10-29 13:13
    关注

    You can use something like:

    func sel(q ...string) (r bson.M) {
        r = make(bson.M, len(q))
        for _, s := range q {
            r[s] = 1
        }
        return
    }
    
    result := c.Find(query).Select(sel("fieldA", "fieldB")).One() 
    // or 
    
    fields := []string{"fieldA","fieldB"}
    result := c.Find(query).Select(sel(fields...)).One() 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作