Convert a field to an array using MongoDB update operation?


To convert a field to an array, use $set operator. Let us first create a collection with documents −

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

Following is the query to display all documents from a collection with the help of find() method −

> db.convertAFieldToAnArrayDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5ce92d7778f00858fb12e91d"), "StudentSubject" : "MongoDB" }

Following is the query to convert a field to an array using update operation with $set:−

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

Let us check the document once again −

> db.convertAFieldToAnArrayDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5ce92d7778f00858fb12e91d"), "StudentSubject" : [ "MongoDB" ] }

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements