Is it possible to set the new object data depending on the actual element in $addToSet?

Is it possible to set the new object data depending on the actual element ? Something like:
{ $addToSet: { “groups.$[elem].votes”: { //new object data = GetObjectData(groups.$[elem].userId) } }

How would the sample look like when using the C# Mongo driver?

Hello @Abra_Sata, welcome to the MongoDB Community forum!

I suggest you post your own data and the code you had tried. Even better, create a new post and include details like sample input document as JSON text, the operation you want to perform and the expected result.

The following is not a valid syntax in the update method:

… GetObjectData(groups.$[elem].userId)

1 Like

Thank you for the reply. You mean that it is not possible to set a dynamic new value for the object, depending on the element (array item) being updated?
I would like to use the approach above, but to be able to set different property values for the array elements (those from the arrayFilters) being updated.

This syntax applies only with the MongoDB update method - not in the JavaScript code you are calling the update method from.

Thanks, I understand. There is no trick to get somehow the information about which array element is being updated?

@Abra_Sata, to update an element in an array, you need to know the value of the element or the field value of the nested document. If you want to know the array element position (e.g., index 4, the fifth element), and use its value in calling another external function, I don’t know if its possible.

The Updates with Aggregation Pipeline feature allows using JavaScript function within an update operation using the $function operator. Maybe you can try using this feature to accommodate your custom function code. Here is a post as an example usage:

Thanks, I will take a look into that post. Do you eventually have a sample about how to implement that functionality with mongodb C# driver? Is it possible to realize this as a bulk write, to update several array entries at a time?

No, I don’t have a sample about the functionality you are looking for using C# driver. Please refer the C# driver reference documentation and APIs. But, you can use bulk write to update individual updates.