Convert a field to an array using update operation in MongoDB


To convert a field to an array, use UPDATE operation inside forEach(). Let us first create a collection with documents −

> db.demo18.insertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e1387fc55d0fc6657d21f0e")
}

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

> db.demo18.find();

This will produce the following output −

{ "_id" : ObjectId("5e1387fc55d0fc6657d21f0e"), "StudentName" : "John" }

Here is the query to convert a field to an array using update operation −

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

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

> db.demo18.find();

This will produce the following output −

{ "_id" : ObjectId("5e1387fc55d0fc6657d21f0e"), "StudentName" : [ "John" ] }

Updated on: 01-Apr-2020

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements