How do I add a value to the top of an array in MongoDB?

MongoDBDatabaseBig Data Analytics

To add a value to the top of an array in MongoDB, you can use unshift() −

yourArrayName.unshift("yourValue");

The above syntax will add the value to the top of an array in MongoDB. Let us first create an array of strings −

> technicalSkills=["Java","MySQL","C","SQL SERVER","ORACLE","PL/SQL"];

This will produce the following output −

[ "Java", "MySQL", "C", "SQL SERVER", "ORACLE", "PL/SQL" ]

Following is the query to add to the top of an array in MongoDB. Here, we will add “MongoDB” to top of an array using unshift() −

> technicalSkills.unshift("MongoDB");

This will produce the following output −

7

Let us check the “MongoDB” has been added to top of an array or not. In order to display the array value, just write the array name at the console −

> technicalSkills

This will produce the following output −

[ "MongoDB", "Java", "MySQL", "C", "SQL SERVER", "ORACLE", "PL/SQL" ]
raja
Published on 30-Apr-2019 09:08:20
Advertisements