Tutorialspoint

1 Answer
Nishtha Thakur

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" ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.