Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse chronological order of struct/results

Just started learning goLang.

Wondering how can we sort an struct elements in reverse order in Go. Let's say, I am getting the results from database something like as:

var results []<someClass>
collection.C(results).Find(bson.M{"<someid>":<id_val>}).All(&results)

Now, I have my database objects/results available in slice results. How can I sort the slice results in reverse order on a column called time?

like image 782
Hemant Bhargava Avatar asked Dec 04 '25 11:12

Hemant Bhargava


1 Answers

Easiest would be to let MongoDB sort the records:

var results []YourType
err := sess.DB("").C("collname").Find(bson.M{"someid": "someidval"}).
    Sort("-timefield").All(&results)

If for some reason you can't or don't want to do this, you may utilize the sort package. You need to implement sort.Interface.

For example:

type YourType struct {
    SomeId    string
    Timestamp time.Time
}

type ByTimestamp []YourType

func (a ByTimestamp) Len() int           { return len(a) }
func (a ByTimestamp) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByTimestamp) Less(i, j int) bool {
    return a[i].Timestamp.After(a[j].Timestamp)
}

This ByTimestamp type is a slice of YourType, and it defines a reverse timestamp order because the Less() method uses Time.After() to decide if element and index i is less than element at index j.

And using it (try it on the Go Playground):

var results []YourType

// Run your MongoDB query here

// Now sort it by Timestamp decreasing:
sort.Sort(ByTimestamp(results))

An alternative implementation for Less() would be to use Time.Before(), but compare element at index j to index i:

func (a ByTimestamp) Less(i, j int) bool {
    return a[j].Timestamp.Before(a[i].Timestamp)
}

Try this variant on the Go Playground.

like image 145
icza Avatar answered Dec 07 '25 06:12

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!