Golang Bson sort parameters in mgo

Glenn Walker picture Glenn Walker · Oct 2, 2015 · Viewed 7.7k times · Source

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??

Answer

OneOfOne picture OneOfOne · Oct 2, 2015

Like this:

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