This program demonstrates usage of sort method of MongoDB in golang
create application directory for golang application, and create init go module as below
mkdir mongodbsort
cd mongodbsort
go mod init github.com/freedomtutorials/mongodbsort
import mongodb-drivers in go module, for this issue the below command
go get go.mongodb.org/mongo-driver
We will be using the below Person structure in this article.
type Person struct
{
ID int
FirstName string
LastName string
Age int
Salary int
}
for this example, the below is the data we are using, prepare slice and insert into MongoDB collection
var persons []Person
persons = append( persons, Person{ ID:1, FirstName:"Michael", LastName:"Ackerman", Age: 26, Salary: 1200})
persons = append( persons, Person{ ID:1, FirstName:"Kayden", LastName:"Brown", Age: 24, Salary: 1200})
persons = append( persons, Person{ ID:1, FirstName:"Dereck", LastName:"Belizaire", Age: 29, Salary: 1300})
persons = append( persons, Person{ ID:1, FirstName:"Galilea", LastName:"Agrinsoni", Age: 23, Salary: 1400})
persons = append( persons, Person{ ID:1, FirstName:"Jeremiah", LastName:"Albarracin", Age: 23, Salary: 1400})
persons = append( persons, Person{ ID:1, FirstName:"Arianna", LastName:"Aliendo", Age: 28, Salary: 2300})
persons = append( persons, Person{ ID:1, FirstName:"Aleida", LastName:"Anderson", Age: 30, Salary: 3000})
persons = append( persons, Person{ ID:1, FirstName:"Calahn", LastName:"Anderson", Age: 33, Salary: 3300})
persons = append( persons, Person{ ID:1, FirstName:"Hafeez", LastName:"Apata", Age: 35, Salary: 2500})
persons = append( persons, Person{ ID:1, FirstName:"Leah", LastName:"Aristhilde", Age: 31, Salary: 2000})
for _, person := range persons {
//fmt.Printf( "%T %T\n", i, person)
collInsertResult, err := coll.InsertOne( context.TODO(), person)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted Single Document: ", collInsertResult.InsertedID)
}
Sort collection on firstname
// set sort field and order, 1 = asc -1 = desc
opts := options.Find()
opts.SetSort(bson.D{{"firstname", -1}})
// pass opts to Find Method
cursor, err := mydataCollection.Find( context.TODO(), bson.M{}, opts)
check for any error
if err != nil {
log.Fatal(err)
}
Read.All from cursor and fill Slice object
var persons []Person
if err = cursor.All( context.TODO(), &persons); err != nil {
log.Fatal(err)
}
close the cursor
cursor.Close( context.TODO())
how to use range in golang
posted on 2022-05-03 08:28:11 - Go lang Tutorials
find variable type in golang
posted on 2022-05-03 05:24:55 - Go lang Tutorials