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" ] }
raja
Published on 14-Jun-2019 15:50:56
Advertisements