Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Bson sort parameters in mgo

Tags:

sorting

go

bson

mgo

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

like image 461
Glenn Walker Avatar asked Oct 02 '15 13:10

Glenn Walker


1 Answers

Like this:

db.C(Collection).Find(Query).Limit(limit).Sort(sortBy...).Iter()
like image 65
OneOfOne Avatar answered Oct 08 '22 08:10

OneOfOne