 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }Advertisements
 