Hier eine kurze Zusammenfassung der typischen CRUD Aktionen gegen eine MongoDB mit GO.
Installation MongoDB Package
go get go.mongodb.org/mongo-driver/mongo
Beispiele
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"reflect"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type DVD struct {
ID primitive.ObjectID `json:"_id" bson:"_id,omitempty"`
Title string `bson:"title",json:"title"`
Year int `bson:"year",json:"year"`
Director string `bson:"director",json:"director"`
Genre string `bson:"genre",json:"genre"`
}
func main() {
// Connect
client, err := mongo.NewClient(options.Client().ApplyURI(("mongodb://127.0.0.1:27017")))
if err != nil {
log.Panic(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Panic(err)
}
defer client.Disconnect(ctx)
db := client.Database("lab")
col := db.Collection("dvds")
// Create Record
record := DVD{
Title: "Jonny is here",
Year: 2022,
Director: "Krusty the clown",
Genre: "Comedy",
}
resultid, err := col.InsertOne(ctx, record)
if err != nil {
log.Panic(err)
}
fmt.Println("Result")
fmt.Println(resultid)
// Get Record
filter := bson.D{{"year", 2022}}
var result DVD
err = col.FindOne(ctx, filter).Decode(&result)
if err != nil {
log.Panic(err)
}
fmt.Println("Result:")
fmt.Println(result)
// Get Records
var results []DVD
cursor, err := col.Find(ctx, bson.D{})
if err = cursor.All(ctx, &results); err != nil {
log.Panic(err)
}
for _, result := range results {
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
log.Panic(err)
}
fmt.Printf("%s\n", output)
}
// Update Record
id, _ := primitive.ObjectIDFromHex("63721740e3cded090bb5311e")
ufilter := bson.D{{"_id", id}}
update := bson.D{{"$set", bson.D{{"title", "Foobar"}}}}
uresult, err := col.UpdateOne(ctx, ufilter, update)
if err != nil {
log.Panic(err)
}
fmt.Println("Update")
fmt.Printf("%v\n", uresult)
// Delete Record
did, _ := primitive.ObjectIDFromHex("637219f767b9212d8e91ef13")
res, err := col.DeleteOne(ctx, bson.M{"_id": did})
if err != nil {
log.Panic(err)
}
fmt.Println("DeleteOne Result TYPE:", reflect.TypeOf(res))
}
