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

Comments

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 Comments

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 ?
nupdate := bson.M{"$pull": bson.M{"workflows": &[]int{} } } this worked ! Thanks

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.