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

huangapple go评论68阅读模式
英文:

How to delete Nth element in MongoDB array with golang?

问题

我需要删除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": []
}
英文:

I need to delete first or second element in expenses

{"_id":{"$oid":"12"},
"chatID":{"$numberInt":"12"},
"expenses":[
   ​{"category":"food","amount":{"$numberDouble":"12.0"}},
   ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
"income":[]}

Smth like expenses[0].Delete()

Result should be like this:

{"_id":{"$oid":"12"},
"chatID":{"$numberInt":"12"},
"expenses":[
   ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
"income":[]}

答案1

得分: 1

你需要使用$unset更新命令,并手动提及数组键名以及其索引。

更新命令:

_, err = collection.UpdateOne(
		ctx,
		bson.D{},  // <- 查找参数
		bson.D{
			{"$unset", bson.D{
				{"expenses."+indexToRemove, 1},  // <- 从`expenses`数组中删除第`indexToRemove`个元素
			}},
		},
	)

完整的Go代码:

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"  // <- 输入要删除的索引,可以是字符串或将其转换为字符串

	_, err = collection.UpdateOne(
		ctx,
		bson.D{},
		bson.D{
			{"$unset", bson.D{
				{"expenses."+indexToRemove, 1},  // <- 从`expenses`数组中删除第`indexToRemove`个元素
			}},
		},
	)
	if err != nil {
		fmt.Println(err)
	}

	err = collection.FindOne(ctx, bson.D{}).Decode(&result)
	fmt.Println(result)
}
英文:

You have to make use of the $unset update command and manually mention the array key name along with its index.

Update Command:

_, err = collection.UpdateOne(
		ctx,
		bson.D{},  // &lt;- Find Parameter
		bson.D{
			{&quot;$unset&quot;, bson.D{
				{&quot;expenses.&quot;+indexToRemove, 1},  // &lt;- Removes `indexToRemove` th element from `expenses` array
			}},
		},
	)

Full Go Code

package main

import (
	&quot;context&quot;
	&quot;fmt&quot;
	&quot;go.mongodb.org/mongo-driver/bson&quot;
	&quot;go.mongodb.org/mongo-driver/mongo&quot;
	&quot;go.mongodb.org/mongo-driver/mongo/options&quot;
	&quot;time&quot;
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	mClient, err := mongo.Connect(ctx, options.Client().ApplyURI(&quot;mongodb://localhost:27017&quot;))

	defer func() {
		if err = mClient.Disconnect(ctx); err != nil {
			panic(err)
		}
	}()

	collection := mClient.Database(&quot;temp&quot;).Collection(&quot;tmp10&quot;)

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

	var result bson.M
	err = collection.FindOne(ctx, bson.D{}).Decode(&amp;result)
	fmt.Println(result)

	indexToRemove := &quot;0&quot;  // &lt;- Input index to remove in string or convert it into string

	_, err = collection.UpdateOne(
		ctx,
		bson.D{},
		bson.D{
			{&quot;$unset&quot;, bson.D{
				{&quot;expenses.&quot;+indexToRemove, 1},  // &lt;- Removes `indexToRemove` th element from `expenses` array
			}},
		},
	)
	if err != nil {
		fmt.Println(err)
	}

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

huangapple
  • 本文由 发表于 2021年11月27日 20:13:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/70134680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定