R
R
Rag'n' Code Man2021-12-16 16:38:49
MongoDB
Rag'n' Code Man, 2021-12-16 16:38:49

How can I change the data type of a String field to [String] in MongoDB while retaining the previous data?

I have a field with phone number phone. Currently, only one phone number can be stored there. But now we need to store several phone numbers, and I need to somehow write a migration for all this.

I tried

db.Clients.updateMany({}, {$set: { phones:  ["$phone"] } })

But instead of substituting the value from the field into the array as the first element phone, he simply substituted this string there.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lssssssssssl, 2021-12-16
@iDmitriyWinX

db.Clients.find({}).forEach(el => {
    db.Clients.updateOne({ _id: el._id }, { $set: { phone: [el.phone] }})
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question