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