Saturday, 24 October 2020

go web app 6 mongodb insert

 
object inserted
//cmd
C:\Users\bob\golang3>go run main.go
&{ObjectID("5f9433922ba504d267c1aad3")}

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)

trainingDatabase := client.Database("sample_training")
gradesCollection := trainingDatabase.Collection("grades")

gradeInsert, err := gradesCollection.InsertOne(ctx, bson.D{
{"student_id", 123},
{"class_id", 456},
{"scores", bson.A{
bson.D{{"exam", 100}},
bson.D{{"quize", 100}},
bson.D{{"homework", 100}},
bson.D{{"homework", 100}},
}},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(gradeInsert)
}

reference:

No comments:

Post a Comment