I still have no idea on how to do it within a single updateMany() but I have a few tips.
Tip 1 - $redact
For
That is what I thought. Fortunately, you may use https://docs.mongodb.com/manual/reference/operator/aggregation/redact/ to produce documents you can share rather than manual edits.
Tip 2 - Don’t use {} query
When doing migration like updateMany({},…), I still want to specify a query that is more restrictive. In your case, I would use the query:
{ 'products.product.type': 'plan',
'products.product.plan_group': { '$type': 'string' } }
This way I would not end up with [[["Old"]]]
rather than ["Old"]
if by mistake I ran the migration more than once.
Tip 3 - Update into a temporary field
Specially, while developing your migration, rather than overwriting your source field plan_group, update a temporary field like updated_plan_group. This way, if your update does not do what it should you still have your original data.
Tip 4 - Use aggregation and $out in temporary collection
Since aggregation is more powerful, I find it easier to write a pipeline that do the migration and simply $out in a temporary collection. May be $merge back into the source collection can be used. With $unwind, working with arrays become easier.
Tip 5 - Write a migration script
Sometimes it is easier to simply read the collection with the driver of your preferred languages and do a bulk write for the update.
Tip 6 - Do not migrate
One of my preferred method. I simply leave the data as is and I add a little hook that modify only the documents that I process in the application. The schema-less nature of MongoDB allows us to do that. In this case, I would only modify the plan_group of CC850732 when and only when I have to do something to CC850732. One big advantage is that the migration does not cause a usage spike on the servers because it occurs during a longer period of time. One is nice, in your case, is that MQL works well. The query
{...plan_group:"Old"}
will match
{...plan_group:"Old"}
as well as
{...plan_group:["Old"]}
.
May be https://docs.mongodb.com/manual/reference/operator/aggregation/function/ can help you. But I am not familiar enough to help you with it.