MongoDB UpdateOne multiple conditions

Hi there,

I am banging my head against the wall, trying to update a document based on multiple conditions.

Would anyone know how to transform this:

filter := bson.D{{"_id", employee.ID}}

Into multiple conditions, such as below (both versions not working):

		filter := bson.D{
			{"$and", bson.D{
				{"_id", employee.ID},
				{"customerid", customerID},
			}},
		}

or (results in: multiple write errors: [{write errors: [{$and must be an array}]}, {}]
)

	filter := bson.D{
		{"$and", bson.D{
			{"_id", employee.ID},
			{"customerid", employee.CompanyID},
		}},
	}

I would be eternally thankful if someone could help me shed some light on this :sunglasses:

Cheers

1 Like

I have not used the client myself but by looking at the error I think this should fix it

	filter := bson.M{
		{"$and": []bson.M{
			bson.M{"_id", employee.ID},
			bson.M{"customerid", employee.CompanyID},
		}},
	}

“$and” operator needs an array so add [] before your query

Edit: I saw the documentation you should be using bson.M and “$and” will be a key not a value like you wrote in your question.

2 Likes

Thanks a million for pointing me in the right direction :smiley:

Finally made it work by using the following:

	filter := bson.M{
		"$and": []bson.M{
			{"_id": employee.ID},
			{"customerid": employee.CompanyID},
		},
	}
1 Like

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