使用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()

是否有一种方法可以将一个字符串数组作为输入,然后使用该数组创建选定的字符串 如果要让我们说这个数组: p>

  var myArray [] string {“ fieldA”,“ fieldB”} 
  code>  
 
 

然后您可以自动创建它: p>

  selectedFields:= bson.M {“ fieldA”:1,“ fieldB”:1}  
  code>  pre> 
 
 

,然后执行查询 p>

  result = c.Find(query).Select(selectedFields)。 一个()
  code>  pre> 
  div>

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()