[Go] Unable to Update or UpdateByID with $set and $unset together

When trying to combine

_, err = d.UpdateByID(ctx, us.UserUUID, bson.M{"$set": updates}, options.Update().SetUpsert(true))

with _, err = d.UpdateByID(ctx, deleteState.UserUUID, bson.M{"$unset": deletes})

into _, err = d.UpdateByID(ctx, us.UserUUID, []bson.M{{"$set": updates}, {"$unset": deletes}}, options.Update().SetUpsert(true))

I get returned multiple write errors: [{write errors: [{$unset specification must be a string or an array}]}, {<nil>}]

I am using Mongo 4.2 on OSX Big Sur with Golang 1.16 and the standard MongoDB driver

Note: I have tried using pipelines, but I get the same error. updates and deletes are both type bson.M{} with keys/values such that updates[key] = value

I will continue to use two separate operations, but I would be interested to know if combining them into a single db call is possible and if not, why.

Best,
Allen

Hello @Allen_Kaplan, welcome to the MongoDB Community forum!

You can perform the update operation’s $set and $unset together within the same Update method. For example:

update := bson.D{
		    { "$set", bson.D{ { "firstname", "Some New Name" }} },
		    { "$unset", bson.D{{ "fullname", "" }} },
	      }

updateResult, err := collection.UpdateByID(context.TODO(), docID, update)

Reference:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.