Mongosh: Copy object to another, nested object

Hey there!

I have a users collection. In this users collection, an array “custom_fields” is contained, which contains further array objects. Now, I would like to move this array “custom_fields” to a new object in the users collection called “customer_file_settings”.

Like: “user.custom_fields” to “user.customer_file_settings.custom_fields”.

I tried the following code:

   { $set: { "customer_file_settings.custom_fields": "$custom_fields" } }

Unfortunately, this did not work. $custom_fields is not presented as the array, but as exactly this plain string.

Do you have any other suggestions?

Thank you! :slight_smile:

You need to use update with aggregation.

1 Like

Thank you! :slight_smile: I found another solution via JS:

var users = db.users.find({});

users.forEach(function(user) {
    { _id: user._id },
    { $set: { "customer_file_settings.custom_fields": user.custom_fields } }

It is certainly slow as you do updateOne on all documents. A bulk write would be more efficient.

You run the risk to have concurrent modification issues since you do the update in a second steps with data that you read in the first step. If user.custom_fields is updated by another process between the time you get the documents in find() and the time you issue the updateOne, you will set customer_file_settings.custom_fields with stale data.

1 Like

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