Select selected query fields by typing with mgo

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

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

      

Then you can create this automatically:

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

      

and then run query

result = c.Find(query).Select(selectedFields).One()

      

+3


source to share


1 answer


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

      

+4


source







All Articles