使用mgo根据输入选择查询的选定字段。

huangapple go评论110阅读模式
英文:

Choose selected fields of query by input using mgo

问题

可以有一个方法,该方法接受一个字符串数组作为输入,并使用该数组创建查询的选定字段。例如,如果你有以下数组:

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

那么你可以自动创建如下所示的选定字段:

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

然后执行查询:

  1. result = c.Find(query).Select(selectedFields).One()
英文:

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:

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

Then you can create this automatically:

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

and then execute the query

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

答案1

得分: 4

你可以使用类似以下的代码:

  1. func sel(q ...string) (r bson.M) {
  2. r = make(bson.M, len(q))
  3. for _, s := range q {
  4. r[s] = 1
  5. }
  6. return
  7. }
  8. result := c.Find(query).Select(sel("fieldA", "fieldB")).One()
  9. // 或者
  10. fields := []string{"fieldA","fieldB"}
  11. result := c.Find(query).Select(sel(fields...)).One()

这段代码的作用是定义了一个名为sel的函数,用于创建一个bson.M类型的映射。在sel函数中,我们将传入的字符串参数作为键,值设置为1,并将其添加到映射中。然后,我们可以使用c.Find(query).Select(sel("fieldA", "fieldB")).One()c.Find(query).Select(sel(fields...)).One()来选择查询结果中的特定字段。

英文:

You can use something like:

  1. func sel(q ...string) (r bson.M) {
  2. r = make(bson.M, len(q))
  3. for _, s := range q {
  4. r
    展开收缩
    = 1
  5. }
  6. return
  7. }
  8. result := c.Find(query).Select(sel("fieldA", "fieldB")).One()
  9. // or
  10. fields := []string{"fieldA","fieldB"}
  11. result := c.Find(query).Select(sel(fields...)).One()

huangapple
  • 本文由 发表于 2014年10月29日 20:03:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/26629862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定