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: 0 specifies insertion at the beginning of the array
  • $each allows 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.

Updated on: 2026-03-15T00:47:45+05:30

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements