Sunday, 25 October 2020

go web app 8 mongodb update

scores are updated
//cmd

C:\Users\bob\golang3>go run main.go
map[_id:ObjectID("5f9433922ba504d267c1aad3") class_id:456 scores:[map[exam:100] map[quize:100] map[homework:100] map[homework:100]] student_id:123]
1  updated

//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)

filterCursor, err := gradesCollection.Find(ctx, bson.M{"student_id": 123, "class_id": 456})
defer filterCursor.Close(ctx)
if err != nil {
log.Fatal(err)
}

var grades []bson.M
if err = filterCursor.All(ctx, &grades); err != nil {
log.Fatal(err)
}
fmt.Println(grades[0])

gradeUpdate, err := gradesCollection.UpdateOne(
ctx,
bson.M{"_id": grades[0]["_id"]},
bson.D{
{"$set", bson.D{{"scores",
bson.A{
bson.D{{"exam", 99}},
bson.D{{"quize", 99}},
bson.D{{"homework", 99}},
bson.D{{"homework", 99}},
}}},
},
},
)
if err != nil {
log.Fatal(err)
}
fmt.Println(gradeUpdate.ModifiedCount, " updated")
}

reference:

No comments:

Post a Comment