Search code examples
mongodbgorandomslicemgo

Randomize order of a MongoDB query in Go


Here is my query :

c := session.DB("searchV").C("video")
var results []BadVideo
err5 := c.Find(nil).All(&results)
fmt.Println("request done")
if err5 != nil {
    panic(err5)
}
var i = 0
for _,badvideo := range results {
}

I would like to randomize the order of browsing the items of the query for making operation on each item of the request ...

So each time I run it, I browse it in a different order.


Solution

  • Manual shuffling

    Here's a simple shuffle algorithm, which shuffles (randomizes) a []BadVido slice:

    func shuffle(r []BadVideo) {
        for i := len(r) - 1; i > 0; i-- {
            j := rand.Intn(i + 1)
            r[i], r[j] = r[j], r[i]
        }
    }
    

    So after you loaded your results, simply call shuffle(results) on it.

    For testing, I will use a simple BadVideo type:

    type BadVideo struct {
        Name string
    }
    
    func main() {
        rand.Seed(time.Now().UnixNano())
        results := []BadVideo{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
        shuffle(results)
        fmt.Println(results)
    }
    

    Output (try it on the Go Playground):

    [{c} {d} {b} {e} {a}]
    

    How it works:

    To shuffle a slice, the shuffle() function randomly selects one element from the slice for each index. It does it like iterating over all elements downward, and selects a random element from the remaining slice (including index of the element we're currently selecting, because random orders also include ones where an element "stays in place"), and using a random index to swaps the element with the chosen random one. The loop goes until i > 0 (and not until i >=0), because if only 1 element left, no need to swap it with itself.

    Using rand.Perm()

    Another variant of shuffle() could take advantage of rand.Perm() which returns a slice containing shuffled numbers. We can use these random numbers to tell how to reorder the results:

    func shuffle(r []BadVideo) {
        r2 := append([]BadVideo(nil), r...)
        for i, j := range rand.Perm(len(r)) {
            r[i] = r2[j]
        }
    }
    

    Try this variant on the Go Playground.

    One thing to note here: before we do the reordering, we have to save the original slice (make a copy of it), so we can select the original elements specified by random indices when writing the results in the slice. I created a copy by appending the complete slice to a nil slice.