3

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
  • myArray is a slice BTW, not an array. Commented Jun 3, 2016 at 17:42

1 Answer 1

4

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() 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.