Wednesday, 21 October 2020

go web app 5 mongodb retrive and query 1

database structure
//cmd -first 5 dataset

C:\Users\bob\golang3>go run main.go
student ID:  0
class ID: 339
grades:  [map[score:78.40446309504266 type:exam] map[score:73.36224783231339 type:quiz] map[score:46.980982486720535 type:homework] map[score:76.67556138656222 type:homework]]
student ID:  0
class ID: 350
grades:  [map[score:91.97520018439039 type:exam] map[score:95.80410375967175 type:quiz] map[score:89.62485475572984 type:homework] map[score:51.621532832724846 type:homework]]
student ID:  0
class ID: 149
grades:  [map[score:84.72636832669608 type:exam] map[score:7.8865616909793435 type:quiz] map[score:22.860114572528147 type:homework] map[score:80.85669686147487 type:homework]]
student ID:  0
class ID: 39
grades:  [map[score:6.267513889635468 type:exam] map[score:23.8466262779109 type:quiz] map[score:42.52700970652198 type:homework] map[score:76.22758120978754 type:homework]]
student ID:  0
class ID: 391
grades:  [map[score:41.25131199553351 type:exam] map[score:91.7351500084582 type:quiz] map[score:24.198828271948415 type:homework] map[score:79.77471812670814 type:homework]]

//main.go
package main

import (
"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://bob:password@cluster0.yvyo2.mongodb.net/test?retryWrites=true&w=majority"))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 100*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)

/*
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
databases, err := client.ListDatabaseNames(ctx, bson.M{})
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
fmt.Print(databases)
*/
trainingDatabase := client.Database("sample_training")
gradesCollection := trainingDatabase.Collection("grades")

cursor, err := gradesCollection.Find(ctx, bson.M{})
/*
if err != nil {
log.Fatal(err)
}
var grades []bson.M
if err = cursor.All(ctx, &grades); err != nil {
log.Fatal(err)
}
fmt.Println(grades)
*/
defer cursor.Close(ctx)

for i := 0; cursor.Next(ctx) && i < 5; i++ {
var grade bson.M
if err = cursor.Decode(&grade); err != nil {
log.Fatal(err)
}
fmt.Println("student ID: ", grade["student_id"])
fmt.Println("class ID:", grade["class_id"])
fmt.Println("grades: ", grade["scores"])
}
}

No comments:

Post a Comment