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


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

Updated on: 30-Jul-2019

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements