Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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