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() 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?