Mongo go driver update with $set $cond aggregation operator works only when wrapped as array

Hi, I tried to update a document with $set and $cond and countered behavior that i cannot understand.

filter := bson.M{
		"job_id": internalJobID,
	}
	update := bson.A{
		bson.M{"$set": bson.M{
			"status": bson.M{
				"$cond": bson.A{
					bson.D{{"$eq", bson.A{"$status", 0}}}, resultStatus, "$status",
				},
			},
		},
		},
	}

	singleResult := ac.HistoryCollection(groupID).FindOneAndUpdate(context.Background(), filter, update)
	if err := singleResult.Err(); err != nil {
		return nil, errors.Wrap(err, errString)
	}

above code works but below update code is not working.

update := bson.M{
		"$set": bson.M{
			"status": bson.M{
				"$cond": bson.A{
					bson.D{{"$eq", bson.A{"$status", 0}}}, resultStatus, "$status",
				},
			},
		},
	}

The difference between two is only wrapping by bson.A (array) or not.
When the below code runs, it write this kind of result, which seems $cond is not recognized as aggregation operator.
image

As all of my update codes are not wrapped by array and it works fine till this time, I wonder what makes difference in this case.

Thanks!

The update command takes as a second argument either a document which indicates this is traditional update modifier syntax, or an array which indicates this will be aggregation pipeline syntax. You are using agg syntax so I would expect it to fail without being wrapped in an array. Or in your case interpret it as regular $set modifier which only accepts subdocument containing field name and field value.

See update command doc.

Asya

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