在Go中删除MongoDB中的数组元素

问题描述 投票:0回答:1

我在MongoDB中有如下数据:

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"rolecode":"DHBK1_ROLE_05","productid":"XYZ_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3","DHBK1_FUNC_4"],"comid":"DHBK1"} {"_id":{"$oid":"5ed0cc67b8d5570916d1ef86"},"rolecode":"DHBK1_ROLE_06","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2","DHBK1_FUNC_3"],"comid":"DHBK1"} {"_id":{"$oid":"5ed0d23cb8d5570916d1f4c8"},"rolecode":"DHBK1_ROLE_09","productid":"LAM_Platform","functioncodelist":["DHBK1_FUNC_1"],"comid":"DHBK1"}

而且我有Mongo shell从数组中删除DHBK1_FUNC_1元素。

这是我的Mongo外壳:

db.company_role_function.update(
  { },
  { $pull: { functioncodelist: { $in: ['DHBK1_FUNC_1'] }}},
  { multi: true }
)

然后我编写Go代码来实现我的Mongo Shell。

这是我的代码:

    package main
    import (
        "context"
        "fmt"
        "strings"
        "time"
        "gopkg.in/mgo.v2"
    )
    func main() {
        var functionCode []string
        functionCode = append(functionCode, "DHBK1_FUNC_1")
        fmt.Println(functionCode)
        deleteArray(functionCode)
     }
    func deleteArray(functionCode []string) {
        session, err := mgo.Dial("mongo_uri_connect")
        if err != nil {
        panic(err)
     }
    c := session.DB("users").C("company_role_function")
    err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true})
    if err != nil {
    fmt.Println(err)
    }
}

当我运行代码时,它显示此错误:

# command-line-arguments
 .\main.go:86:16: too many arguments in call to c.Update
    have (primitive.M, primitive.M, primitive.M)
    want (interface {}, interface {})

当我删除bson.M{"multi": true}行中的err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true})时,它起作用了,但是没有删除任何元素DHBK1_FUNC_1

谢谢

mongodb go mgo mongo-go
1个回答
0
投票

我尝试使用Mongo-go-driver,它起作用了。

但是Mgo仍然不起作用。

这是我的代码:

   func deleteArrayDriver(functionCode []string) {
   ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
   client, err := mongo.Connect(ctx, options.Client().ApplyURI("link"))
   if err != nil {
       panic(err)
   }
   defer client.Disconnect(ctx)
   database := client.Database("users")
   users := database.Collection("company_role_function")
   _, err = users.UpdateMany(ctx, bson.D{{}}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}})
   if err != nil {
       panic(err)
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.