Search code examples
mongodbgomgo

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


Solution

  • 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.