I need to remove and get all elements of an array in mongodb. I found $pull and $pullAll but they require query condition, how to remove all elements without condition?
The code not work, elements still exist after the $pull:
var UserId = 123
type Event struct {
UserId uint64 `gorm:"uniqueIndex"`
Array [][]byte
}
func main() {
var DB_NAME = "test"
var ctx = context.Background()
client, _ := mongo.Connect(
ctx, options.Client().ApplyURI("mongodb://localhost"))
col := client.Database("test").Collection(`Test`)
{ // pull items
r := col.FindOneAndUpdate(ctx, bson.M{
`UserId`: UserId,
}, bson.M{
`$pull`: bson.M{
`Array`: nil,
},
}, options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.Before))
if r.Err() != nil {
panic(r.Err())
}
}
}
Edit:
I found $set': bson.M{"Array": [][]byte{}} does the job, is $pull capable of doing this? Which performance is better?