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

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

How to delete Nth element in MongoDB array with golang?

问题

我需要删除expenses中的第一个或第二个元素。

  1. {
  2. "_id": {"$oid": "12"},
  3. "chatID": {"$numberInt": "12"},
  4. "expenses": [
  5. {"category": "food", "amount": {"$numberDouble": "12.0"}},
  6. {"category": "food", "amount": {"$numberDouble": "14.0"}}
  7. ],
  8. "income": []
  9. }

类似于 expenses[0].Delete()

结果应该是这样的:

  1. {
  2. "_id": {"$oid": "12"},
  3. "chatID": {"$numberInt": "12"},
  4. "expenses": [
  5. {"category": "food", "amount": {"$numberDouble": "14.0"}}
  6. ],
  7. "income": []
  8. }
英文:

I need to delete first or second element in expenses

  1. {"_id":{"$oid":"12"},
  2. "chatID":{"$numberInt":"12"},
  3. "expenses":[
  4. ​{"category":"food","amount":{"$numberDouble":"12.0"}},
  5. ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
  6. "income":[]}

Smth like expenses[0].Delete()

Result should be like this:

  1. {"_id":{"$oid":"12"},
  2. "chatID":{"$numberInt":"12"},
  3. "expenses":[
  4. ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
  5. "income":[]}

答案1

得分: 1

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

更新命令:

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

完整的Go代码:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "go.mongodb.org/mongo-driver/bson"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "time"
  9. )
  10. func main() {
  11. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  12. defer cancel()
  13. mClient, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
  14. defer func() {
  15. if err = mClient.Disconnect(ctx); err != nil {
  16. panic(err)
  17. }
  18. }()
  19. collection := mClient.Database("temp").Collection("tmp10")
  20. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
  21. defer cancel()
  22. var result bson.M
  23. err = collection.FindOne(ctx, bson.D{}).Decode(&result)
  24. fmt.Println(result)
  25. indexToRemove := "0" // <- 输入要删除的索引,可以是字符串或将其转换为字符串
  26. _, err = collection.UpdateOne(
  27. ctx,
  28. bson.D{},
  29. bson.D{
  30. {"$unset", bson.D{
  31. {"expenses."+indexToRemove, 1}, // <- 从`expenses`数组中删除第`indexToRemove`个元素
  32. }},
  33. },
  34. )
  35. if err != nil {
  36. fmt.Println(err)
  37. }
  38. err = collection.FindOne(ctx, bson.D{}).Decode(&result)
  39. fmt.Println(result)
  40. }
英文:

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

Update Command:

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

Full Go Code

  1. package main
  2. import (
  3. &quot;context&quot;
  4. &quot;fmt&quot;
  5. &quot;go.mongodb.org/mongo-driver/bson&quot;
  6. &quot;go.mongodb.org/mongo-driver/mongo&quot;
  7. &quot;go.mongodb.org/mongo-driver/mongo/options&quot;
  8. &quot;time&quot;
  9. )
  10. func main() {
  11. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  12. defer cancel()
  13. mClient, err := mongo.Connect(ctx, options.Client().ApplyURI(&quot;mongodb://localhost:27017&quot;))
  14. defer func() {
  15. if err = mClient.Disconnect(ctx); err != nil {
  16. panic(err)
  17. }
  18. }()
  19. collection := mClient.Database(&quot;temp&quot;).Collection(&quot;tmp10&quot;)
  20. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
  21. defer cancel()
  22. var result bson.M
  23. err = collection.FindOne(ctx, bson.D{}).Decode(&amp;result)
  24. fmt.Println(result)
  25. indexToRemove := &quot;0&quot; // &lt;- Input index to remove in string or convert it into string
  26. _, err = collection.UpdateOne(
  27. ctx,
  28. bson.D{},
  29. bson.D{
  30. {&quot;$unset&quot;, bson.D{
  31. {&quot;expenses.&quot;+indexToRemove, 1}, // &lt;- Removes `indexToRemove` th element from `expenses` array
  32. }},
  33. },
  34. )
  35. if err != nil {
  36. fmt.Println(err)
  37. }
  38. err = collection.FindOne(ctx, bson.D{}).Decode(&amp;result)
  39. fmt.Println(result)
  40. }

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:

确定