Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 the $push operator with $each and $position: 0 to insert elements at the beginning of an array field in a document.
Syntax
db.collection.updateOne(
{ query },
{
$push: {
arrayField: {
$each: ["newValue"],
$position: 0
}
}
}
);
Sample Data
Let us first create a document with an array of technical skills ?
db.skills.insertOne({
_id: 1,
name: "John",
technicalSkills: ["Java", "MySQL", "C", "SQL SERVER", "ORACLE", "PL/SQL"]
});
Example: Add MongoDB to Top of Array
Now, let's add "MongoDB" to the beginning of the technicalSkills array ?
db.skills.updateOne(
{ _id: 1 },
{
$push: {
technicalSkills: {
$each: ["MongoDB"],
$position: 0
}
}
}
);
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}
Verify Result
Let's verify that "MongoDB" has been added to the top of the array ?
db.skills.findOne({ _id: 1 });
{
"_id": 1,
"name": "John",
"technicalSkills": [
"MongoDB",
"Java",
"MySQL",
"C",
"SQL SERVER",
"ORACLE",
"PL/SQL"
]
}
Key Points
-
$position: 0specifies insertion at the beginning of the array -
$eachallows you to add multiple values at once - This approach works on document fields, not standalone JavaScript arrays
Conclusion
Use $push with $each and $position: 0 to add values to the top of an array field in MongoDB documents. This method provides precise control over array element positioning.
Advertisements
