go-mongo-driver测试修改数组元素,添加数组元素,删除数组元素

package src

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// Wendang 测试修改数组元素,添加数组元素,删除数组元素
type Wendang struct {
    ID    primitive.ObjectID `bson:"_id,omitempty"`
    Name  string             `bson:"name,omitempty"`
    Shuzu []string           `bson:"shuzu,omitempty"`
}

//Shanchu 删除数组
func Shanchu(c *gin.Context) {

    collection := Lianjie("wendang")
    id, _ := primitive.ObjectIDFromHex("5f55a851b4a4625d9c8051b7")
    filter := bson.M{"_id": id}
    // filter := bson.M{"name": "x2"}
    update := bson.M{"$pull": bson.M{"shuzu": "tt"}} //删除数组元素
    // update := bson.M{"$push": bson.M{"shuzu": "tt"}} //添加数组元素

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

    updateResult, err := collection.UpdateOne(ctx, filter, update)
    if err != nil {
        log.Println(err)
    }
    c.JSON(http.StatusOK, gin.H{"value": updateResult.ModifiedCount})
}

// Inserttest 添加数组
func Inserttest(c *gin.Context) {

    sz := []string{"qq", "ee", "tt"}

    wend := Wendang{
        ID:    primitive.NewObjectID(),
        Name:  "x",
        Shuzu: sz,
    }

    collection := Lianjie("wendang")
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    res, err := collection.InsertOne(ctx, wend)
    if err != nil {
        log.Println(err)
    }
    id := res.InsertedID
    fmt.Println("---------------")
    fmt.Println(id)
    c.JSON(http.StatusOK, gin.H{"value": id})
}

// Test1 修改数组
func Test1(c *gin.Context) {
    coll := Lianjie("wendang")

    filter := bson.M{"name": "aaa", "shuzu": "test2"}
    update := bson.M{"shuzu.$[item]": "test23"}
    arrayFilter := bson.M{"item": "test2"}

    // coll 是 mongo 的 Collection,下面内容不需要修改。
    res := coll.FindOneAndUpdate(context.Background(),
        filter,
        bson.M{"$set": update},
        options.FindOneAndUpdate().SetArrayFilters(
            options.ArrayFilters{
                Filters: []interface{}{
                    arrayFilter,
                },
            },
        ))

    if res.Err() != nil {
        // log error
        log.Println(res.Err())
    }

    log.Println(res.Err())

    c.JSON(http.StatusOK, gin.H{"value": "finsh"})
}

你可能感兴趣的:(go-mongo-driver测试修改数组元素,添加数组元素,删除数组元素)