Golang Bson sort parameters in mgo

烂漫一生 提交于 2019-12-23 10:52:41

问题


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:


Like this:

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


来源:https://stackoverflow.com/questions/32908186/golang-bson-sort-parameters-in-mgo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!