Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
$setoperator 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.
Advertisements
