Bussiere
Bussiere

Reputation: 1154

mgo translation of sort _id : -1

in a classic mongodb query i will do a :

.sort("_id":-1)

how to do it with mgo ?

err := C.Find(bson.M{"Receiver": userId}).Sort("_id":-1).All(&result)

is not working

Regards and Thanks

Upvotes: 1

Views: 2052

Answers (2)

Shaxboz
Shaxboz

Reputation: 19

_id: -1 `This mean is reverse in terms of id`

Upvotes: 1

icza
icza

Reputation: 418435

A sequence of sort operations is simply translated like this:

In MongoDB query:

.sort({"_id:" 1, "name": 1})

Using mgo:

err := C.Find(bson.M{"Receiver": userId}).Sort("_id", "name").All(&result)

If any of the sort operations needs to be done in reverse order, you use -1 in MongoDB query:

.sort({"_id:" -1, "name": -1})

This is transated to a simple '-' sign before the field name in mgo:

err := C.Find(bson.M{"Receiver": userId}).Sort("-_id", "-name").All(&result)

This is documented at Query.Sort():

func (q *Query) Sort(fields ...string) *Query

Sort asks the database to order returned documents according to the provided field names. A field name may be prefixed by - (minus) for it to be sorted in reverse order.

Upvotes: 3

Related Questions