Insert to specific index for MongoDB array?

To insert an element at a specific index in a MongoDB array, use the $push operator combined with $each and $position modifiers. This allows precise control over where new elements are inserted in the array.

Syntax

db.collection.update(
    { _id: ObjectId("document_id") },
    { 
        $push: {
            arrayField: {
                $each: [ "newElement" ],
                $position: index
            }
        }
    }
);

Sample Data

db.insertToSpecificIndexDemo.insertMany([
    {
        "StudentName": "Larry",
        "StudentSubjects": ["MySQL", "Java"]
    },
    {
        "StudentName": "Chris",
        "StudentSubjects": ["C++", "C"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9d2562a629b87623db1b2c"),
        ObjectId("5c9d2573a629b87623db1b2d")
    ]
}

Display Current Documents

db.insertToSpecificIndexDemo.find().pretty();
{
    "_id": ObjectId("5c9d2562a629b87623db1b2c"),
    "StudentName": "Larry",
    "StudentSubjects": [
        "MySQL",
        "Java"
    ]
}
{
    "_id": ObjectId("5c9d2573a629b87623db1b2d"),
    "StudentName": "Chris",
    "StudentSubjects": [
        "C++",
        "C"
    ]
}

Example: Insert at Index 0 (Beginning)

Insert "MongoDB" at the beginning of Chris's StudentSubjects array ?

db.insertToSpecificIndexDemo.update(
    { _id: ObjectId("5c9d2573a629b87623db1b2d") },
    { 
        $push: {
            StudentSubjects: {
                $each: [ "MongoDB" ],
                $position: 0
            }
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.insertToSpecificIndexDemo.find().pretty();
{
    "_id": ObjectId("5c9d2562a629b87623db1b2c"),
    "StudentName": "Larry",
    "StudentSubjects": [
        "MySQL",
        "Java"
    ]
}
{
    "_id": ObjectId("5c9d2573a629b87623db1b2d"),
    "StudentName": "Chris",
    "StudentSubjects": [
        "MongoDB",
        "C++",
        "C"
    ]
}

Key Points

  • $position: 0 inserts at the beginning of the array
  • $position: -1 inserts at the end (same as normal $push)
  • $each is required even when inserting a single element
  • Position values greater than array length append to the end

Conclusion

Use $push with $each and $position modifiers to insert elements at specific array indexes. The $position value determines the exact insertion point, with 0 being the beginning of the array.

Updated on: 2026-03-15T00:36:34+05:30

594 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements