1

This is with reference to

How to remove a document inside an array in mongodb using $pull

I need to remove empty sub arrays. I need to code this query in go lang

db.getCollection('workflows').update({<find condition>}, {$pull: {"workflows":[]  } }   )

So I've written the below code

nquery := bson.D {
    {"level", "application"},
    {"workflowName", workflowName},
    {"applicationName", applicationName},
}
nupdate := bson.M{"$pull": bson.M{"workflows":"[]"}}
UpdateOne(getContext(), nquery, nupdate)

The result of UpdateOne shows my query has matched but hasn't modified anything. So I'm guessing there is some problem with the nupdate. What am I doing wrong ?

The UpdateOne function is part of the mongo-driver for go lang

2 Answers 2

2

"[]" is not an empty array in the query, it's a string having an opening and closing square brackets.

The MongoDB empty array can be "modeled" with an empty slice in Go, e.g. with a value of type []interface{}, so a composite literal of this type is []interface{}{}.

So use this:

nupdate := bson.M{"$pull": bson.M{"workflows": []interface{}{}}}
0
1

The square brackets "[]" shall not be in quotes since now they are interpreted as string ... , they need to be added just as square brackets [] and require in golang: &[]int{} to be translated by the mongo goland driver to empty array ...

2
  • Tried nupdate := bson.M{"$pull": bson.M{"workflows":[] } } , it says syntax error: unexpected }, expecting type go. Sorry I'm new to go, so is this correct ?
    – Abbas
    Jan 17, 2021 at 12:50
  • 1
    nupdate := bson.M{"$pull": bson.M{"workflows": &[]int{} } } this worked ! Thanks
    – Abbas
    Jan 17, 2021 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.