Skip to content

Go-MongoDB

MongoDB ist eine dokumentenorientierte NoSQL-Datenbank. In diesem Artikel wird die Verwendung von MongoDB mit Go vorgestellt.

Installation

Zuerst muss der MongoDB-Treiber installiert werden.

bash
go get go.mongodb.org/mongo-driver/mongo

Verbindung herstellen

go
package main

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

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        log.Fatal(err)
    }

    if err := client.Ping(ctx, nil); err != nil {
        log.Fatal(err)
    }

    fmt.Println("Verbunden mit MongoDB!")
}

Dokument einfügen

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

type Person struct {
    Name string `bson:"name"`
    Age  int    `bson:"age"`
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    person := Person{Name: "Alice", Age: 25}
    result, err := collection.InsertOne(ctx, person)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Eingefügt mit ID: %v\n", result.InsertedID)
}

Mehrere Dokumente einfügen

go
package main

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

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    people := []interface{}{
        bson.M{"name": "Bob", "age": 30},
        bson.M{"name": "Charlie", "age": 35},
    }

    result, err := collection.InsertMany(ctx, people)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Eingefügte IDs: %v\n", result.InsertedIDs)
}

Dokument finden

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    var result bson.M
    err := collection.FindOne(ctx, bson.M{"name": "Alice"}).Decode(&result)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Gefunden: %v\n", result)
}

Mehrere Dokumente finden

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    cursor, err := collection.Find(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    defer cursor.Close(ctx)

    var results []bson.M
    if err := cursor.All(ctx, &results); err != nil {
        log.Fatal(err)
    }

    for _, result := range results {
        fmt.Printf("Gefunden: %v\n", result)
    }
}

Dokument aktualisieren

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    filter := bson.M{"name": "Alice"}
    update := bson.M{"$set": bson.M{"age": 26}}

    result, err := collection.UpdateOne(ctx, filter, update)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Aktualisierte Dokumente: %d\n", result.ModifiedCount)
}

Dokument löschen

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    filter := bson.M{"name": "Alice"}

    result, err := collection.DeleteOne(ctx, filter)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Gelöschte Dokumente: %d\n", result.DeletedCount)
}

Index erstellen

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    indexModel := mongo.IndexModel{
        Keys:    bson.D{{"name", 1}},
        Options: options.Index().SetUnique(true),
    }

    result, err := collection.Indexes().CreateOne(ctx, indexModel)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Index erstellt: %s\n", result)
}

Aggregation

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("test").Collection("people")

    pipeline := mongo.Pipeline{
        {{"$match", bson.M{"age": bson.M{"$gte": 30}}}},
        {{"$group", bson.M{
            "_id":   nil,
            "count": bson.M{"$sum": 1},
        }}},
    }

    cursor, err := collection.Aggregate(ctx, pipeline)
    if err != nil {
        log.Fatal(err)
    }
    defer cursor.Close(ctx)

    var results []bson.M
    if err := cursor.All(ctx, &results); err != nil {
        log.Fatal(err)
    }

    for _, result := range results {
        fmt.Printf("Ergebnis: %v\n", result)
    }
}

Transaktionen

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() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

    err := client.UseSession(ctx, func(ctx context.Context) error {
        sessionCtx := mongo.SessionFromContext(ctx)
        err := sessionCtx.StartTransaction()
        if err != nil {
            return err
        }

        collection := client.Database("test").Collection("people")

        _, err = collection.InsertOne(sessionCtx, bson.M{"name": "David", "age": 40})
        if err != nil {
            sessionCtx.AbortTransaction(sessionCtx)
            return err
        }

        err = sessionCtx.CommitTransaction(sessionCtx)
        if err != nil {
            return err
        }

        return nil
    })

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Transaktion erfolgreich!")
}

Golang by www.golangdev.cn edit