1

I have data in MongoDB like below:

{"_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"}

And I have Mongo shell to remove DHBK1_FUNC_1 element from array.

Here is my Mongo shell:

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

Then I write Go code to implement my Mongo shell.

Here is my code:

    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)
    }
}

When I run my code, it showed this error:

# 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 {})

When I remove bson.M{"multi": true} in line err = c.Update(bson.M{}, bson.M{"$pull": bson.M{"functioncodelist": bson.M{"$in": functionCode}}}, bson.M{"multi": true}), it worked but doesn't remove any element DHBK1_FUNC_1.

Thank you

1 Answer 1

1

I try to use Mongo-go-driver and it worked.

But Mgo still doesn't work.

Here is my code:

   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)
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.