UPDATED ANSWER AUGUST 2023
MONGODB V7.0
1- Query 01
The save() function is depreciated in new MongoDB releases, and it won't work.So instead of save() we can use update() in the following way
Let's assume our collection name is products
db.products.find({}).forEach( function(x)
{
x.field = [ x.field ];
db.products.update( { _id : x._id } , { $set:{ field : x.field } } );
});
The field is the property of the schema you want to convert from string to string[], and want to add the old present values into new string[]
When you will run this query in mongosh, you will not get nay response, after running this query, you have to again run a find query to check the updated results, or if you have any GUI(i.e mongodb compass) ,you can check there as well.
02- Query 02
There's another workaround query with updateMany() , which will return some response after you run the query
db.products.updateMany({}, [
{
$set: {
field: {
$map: {
input: ["A"], // A dummy array to iterate over once
as: "el",
in: "$field"
}
}
}
}
]);
1-$map: This is an aggregation operator that allows you to apply a specified expression to each element of an array. In this case, we are using it to create a new array field containing the value of the field.
2-input: ["A"]: This is a dummy array containing a single element ("A"). It's used to provide a source for the $map operation. Since we are not using the actual elements of the array, it serves as a placeholder.
03-as: "el": This defines an alias ("el") for the current element during the $map operation. In this context, it's not actually used, but it's required syntax for the $map operation.
04-in: "$field": This is the expression that specifies what to do with each element of the dummy array. Here, we are using the value of the existing field in each document to create a new array.