Search code examples
mongodbgomgomongo-go

How to perform Find, Distinct & Sort all together using go mongo driver


I have a command which is made using "labix.org/v2/mgo" library

err = getCollection.Find(bson.M{}).Sort("department").Distinct("department", &listedDepartment)

this is working fine. But now I'm moving to the official golang mongo-driver "go.mongodb.org/mongo-driver/mongo" and I want to run this command in that library but there is no direct function that I can use with Find then Sort then Distinct. How can I achieve this command using this mongo-driver. The variable listedDepartment is type of []string. Please suggest me know the solutions.


Solution

  • You may use Collection.Distinct() but it does not yet support sorting:

    // Obtain collection:
    c := client.Database("dbname").Collection("collname")
    
    ctx := context.Background()
    results, err := c.Distinct(ctx, "department", bson.M{})
    

    It returns a value of type []interface{}. If you know it contains string values, you may use a loop and type assertions to obtain the string values like this:

    listedDepartment = make([]string, len(results))
    for i, v := range results {
        listedDepartment[i] = v.(string)
    }
    

    And if you need it sorted, simply sort the slice:

    sort.Strings(listedDepartment)