Re: mgo: sort on multiple fields

1,443 views
Skip to first unread message

Gustavo Niemeyer

unread,
Mar 13, 2012, 10:42:40 PM3/13/12
to Ivan Daunis, mgo-...@googlegroups.com
Hey Ivan,

> Thanks for this awesome driver!

You're very welcome! :)

> Is it possible to use multiple fields with Sort() in mgo? it works on the
> mongo console but mgo seems to use only the last field.

It is. You can use exactly the same scheme that is available with
MongoDB itself. For example:

iter := coll.Find(nil).Sort(bson.D{{"field1", 1}, {"field2", -1}}).Iter()

Note that in this case you need to use bson.D rather than bson.M,
because the latter is a Go map, and its elements aren't ordered.

Just yesterday I was actually pondering about a slightly different
scheme as well, for making sorting a bit simpler. You can expect
improvements in this area in the upcoming release.

--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/plus
http://niemeyer.net/twitter
http://niemeyer.net/blog

-- I'm not absolutely sure of anything.

Gustavo Niemeyer

unread,
Mar 15, 2012, 2:00:47 PM3/15/12
to Ivan Daunis, mgo-...@googlegroups.com
Hey Ivan,

On Thu, Mar 15, 2012 at 14:12, Ivan Daunis <ida...@gmail.com> wrote:
> Thank you so much, then bson.D really make sense here.
> It would probably be a good idea to add this example in the documentation

That's great to hear, and indeed it needs better examples.

> for Sort(). The only thing I had to do is to add the field "Name" and
> "Value" in order to compile it correctly
>
> iter := coll.Find(nil).Sort(bson.D{{Name:"field1", Value:1},
> {Name:"field2",Value:-1}}).Iter()

That's not necessary. Those are the two only fields this struct has,
so this will certainly work as well:

iter := coll.Find(nil).Sort(bson.D{{"field1", 1}, {"field2", -1}}).Iter()

--

Reply all
Reply to author
Forward
0 new messages