亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用golang刪除MongoDB數組中的第N個元素?

如何使用golang刪除MongoDB數組中的第N個元素?

Go
森欄 2022-10-17 15:43:26
我需要刪除第一個或第二個元素expenses{"_id":{"$oid":"12"},"chatID":{"$numberInt":"12"},"expenses":[   {"category":"food","amount":{"$numberDouble":"12.0"}},   {"category":"food","amount":{"$numberDouble":"14.0"}}],"income":[]}喜歡expenses[0].Delete()結果應該是這樣的:{"_id":{"$oid":"12"},"chatID":{"$numberInt":"12"},"expenses":[   {"category":"food","amount":{"$numberDouble":"14.0"}}],"income":[]}
查看完整描述

1 回答

?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

您必須使用$unset更新命令并手動提及數組鍵名及其索引。


更新命令:


_, err = collection.UpdateOne(

        ctx,

        bson.D{},  // <- Find Parameter

        bson.D{

            {"$unset", bson.D{

                {"expenses."+indexToRemove, 1},  // <- Removes `indexToRemove` th element from `expenses` array

            }},

        },

    )

完整的代碼


package main


import (

    "context"

    "fmt"

    "go.mongodb.org/mongo-driver/bson"

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

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

    "time"

)


func main() {

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

    defer cancel()

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


    defer func() {

        if err = mClient.Disconnect(ctx); err != nil {

            panic(err)

        }

    }()


    collection := mClient.Database("temp").Collection("tmp10")


    ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)

    defer cancel()


    var result bson.M

    err = collection.FindOne(ctx, bson.D{}).Decode(&result)

    fmt.Println(result)


    indexToRemove := "0"  // <- Input index to remove in string or convert it into string


    _, err = collection.UpdateOne(

        ctx,

        bson.D{},

        bson.D{

            {"$unset", bson.D{

                {"expenses."+indexToRemove, 1},  // <- Removes `indexToRemove` th element from `expenses` array

            }},

        },

    )

    if err != nil {

        fmt.Println(err)

    }


    err = collection.FindOne(ctx, bson.D{}).Decode(&result)

    fmt.Println(result)

}


查看完整回答
反對 回復 2022-10-17
  • 1 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號