Convert a field to an array using MongoDB update operation?

To convert a field to an array in MongoDB, use the $set operator to replace the existing field value with an array containing that value. This is useful when you need to transform single values into arrays for future operations.

Syntax

db.collection.update(
    { _id: ObjectId("id") },
    { $set: { "fieldName": [existingValue] } }
)

Sample Data

Let us first create a collection with a document having a string field ?

db.convertAFieldToAnArrayDemo.insertOne({
    "StudentSubject": "MongoDB"
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ce92d7778f00858fb12e91d")
}

Display the document to see its current structure ?

db.convertAFieldToAnArrayDemo.find();
{ "_id": ObjectId("5ce92d7778f00858fb12e91d"), "StudentSubject": "MongoDB" }

Example: Convert String Field to Array

Use forEach() to iterate through documents and convert the field to an array ?

db.convertAFieldToAnArrayDemo.find().forEach(function(myDocument) {
    db.convertAFieldToAnArrayDemo.update(
        { _id: myDocument._id },
        { $set: { "StudentSubject": [myDocument.StudentSubject] } }
    );
});

Verify Result

Check the document after conversion ?

db.convertAFieldToAnArrayDemo.find();
{ "_id": ObjectId("5ce92d7778f00858fb12e91d"), "StudentSubject": ["MongoDB"] }

Key Points

  • The $set operator replaces the field value with the new array format.
  • Use forEach() to process multiple documents that need field conversion.
  • The original value becomes the first element in the new array.

Conclusion

Converting fields to arrays using $set is straightforward − wrap the existing value in square brackets. This transformation prepares your data structure for array operations like $push or $addToSet.

Updated on: 2026-03-15T01:34:23+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements