我需要洗掉第一個或第二個元素 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":[]}
uj5u.com熱心網友回復:
您必須使用$unsetupdate 命令并手動提及陣列鍵名稱及其索引。
更新命令:
_, 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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371088.html
上一篇:RabbitMQ佇列長度始終為0
