如何使用golang删除MongoDB数组中的第N个元素?

我需要删除第一个或第二个元素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":[]}


森栏
浏览 147回答 1
1回答

HUH函数

您必须使用$unset更新命令并手动提及数组键名及其索引。更新命令:_, err = collection.UpdateOne(&nbsp; &nbsp; &nbsp; &nbsp; ctx,&nbsp; &nbsp; &nbsp; &nbsp; bson.D{},&nbsp; // <- Find Parameter&nbsp; &nbsp; &nbsp; &nbsp; bson.D{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"$unset", bson.D{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"expenses."+indexToRemove, 1},&nbsp; // <- Removes `indexToRemove` th element from `expenses` array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }},&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; )完整的代码package mainimport (&nbsp; &nbsp; "context"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "go.mongodb.org/mongo-driver/bson"&nbsp; &nbsp; "go.mongodb.org/mongo-driver/mongo"&nbsp; &nbsp; "go.mongodb.org/mongo-driver/mongo/options"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)&nbsp; &nbsp; defer cancel()&nbsp; &nbsp; mClient, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))&nbsp; &nbsp; defer func() {&nbsp; &nbsp; &nbsp; &nbsp; if err = mClient.Disconnect(ctx); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; collection := mClient.Database("temp").Collection("tmp10")&nbsp; &nbsp; ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)&nbsp; &nbsp; defer cancel()&nbsp; &nbsp; var result bson.M&nbsp; &nbsp; err = collection.FindOne(ctx, bson.D{}).Decode(&result)&nbsp; &nbsp; fmt.Println(result)&nbsp; &nbsp; indexToRemove := "0"&nbsp; // <- Input index to remove in string or convert it into string&nbsp; &nbsp; _, err = collection.UpdateOne(&nbsp; &nbsp; &nbsp; &nbsp; ctx,&nbsp; &nbsp; &nbsp; &nbsp; bson.D{},&nbsp; &nbsp; &nbsp; &nbsp; bson.D{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"$unset", bson.D{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"expenses."+indexToRemove, 1},&nbsp; // <- Removes `indexToRemove` th element from `expenses` array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }},&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; )&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; }&nbsp; &nbsp; err = collection.FindOne(ctx, bson.D{}).Decode(&result)&nbsp; &nbsp; fmt.Println(result)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go