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
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: 0inserts at the beginning of the array -
$position: -1inserts at the end (same as normal $push) -
$eachis 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.
Advertisements
