Saturday, 24 October 2020

go web app 7 mongodb query bson array

data contains bson array
//cmd

C:\Users\bob\golang3>go run main.go
student ID:  123
class ID: 456
grades:
exam :  100
quize :  100
homework :  100
homework :  100

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)

filterCursor, err := gradesCollection.Find(ctx, bson.M{"student_id": 123, "class_id": 456})
defer filterCursor.Close(ctx)
if err != nil {
log.Fatal(err)
}
for filterCursor.Next(ctx) {
var grade bson.M
if err = filterCursor.Decode(&grade); err != nil {
log.Fatal(err)
}
fmt.Println("student ID: ", grade["student_id"])
fmt.Println("class ID:", grade["class_id"])
fmt.Println("grades: ")
scores := grade["scores"].(bson.A)

for _, score := range scores {
for k, v := range score.(bson.M) {
fmt.Println(k, ": ", v)
}
}
}
}
 
reference:

go map

No comments:

Post a Comment