在mgo中对Golang的Bson排序参数进行排序。

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

Golang Bson sort parameters in mgo

问题

我正在尝试将多个排序查询传递给mgo包的"Sort"参数(请参阅https://godoc.org/labix.org/v2/mgo#Query.Sort)。

如果参数是动态的(当前保存在一个切片中),我该如何将其转换为有效的排序字符串。

一个有效的示例是:

db.C(Collection).Find(Query).Limit(limit).Sort("-created_when", "-title").Iter()

但是,如果"-created_when"和"-title"保存在一个切片中,并且我尝试使用切片连接,如下所示:

sortBy := []string{"-created_when", "title"}
db.C(Collection).Find(Query).Limit(limit).Sort(strings.Join(sortBy, ",")).Iter()

查询将无法正确工作。

我该如何将切片中的任意字段转换为所需的.Sort([string1], [string2], ...)格式?

英文:

I am trying to pass a multiple sort query to the "Sort" parameter of the mgo package (see https://godoc.org/labix.org/v2/mgo#Query.Sort).

If the parameters are dynamic (currently held in a slice), how can I translate that into a valid sort string.

A working example would be:

db.C(Collection).Find(Query).Limit(limit).Sort("-created_when", "-title").Iter()

But if "-created_when" and "-title" are held in a slice, and I try using a slice join like:

sortBy := []string{"-created_when", "title"}
db.C(Collection).Find(Query).Limit(limit).Sort(strings.Join(sortBy, ",")).Iter()

The query doesn't work correctly.

How can I translate the arbitrary fields in the slice into the .Sort([string1], [string2], ...) format required??

答案1

得分: 10

像这样:

db.C(集合).查找(查询).限制(限制数).排序(排序方式...).迭代()
英文:

Like this:

db.C(Collection).Find(Query).Limit(limit).Sort(sortBy...).Iter()

huangapple
  • 本文由 发表于 2015年10月2日 21:23:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/32908186.html
匿名

发表评论

匿名网友

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

确定