Search code examples
arraysmongodbpositionpushprepend

How do I prepend an object to the top position of an array?


If I have the following array in a MongoDb doc:

"example": {
    [
        "number": 5,
        "someValue": "V"
    ],
    [
        "number": 7,
        "someValue": "H"
    ]
}

How would i add the array below to the top of the one above:

[
     "number": 3,
     "someValue": "S"
]

So that the original array becomes:

"example": {
    [
        "number": 3,
        "someValue": "S"
    ],
    [
        "number": 5,
        "someValue": "V"
    ],
    [
        "number": 7,
        "someValue": "H"
    ]
}

Solution

  • you can achieve this with the options of the $push operator like this :

    db.collection.update({},
    {  
       $push:{  
          "arr":{  
             $each:[  
                {  
                   "number": 3,
                   "someValue": "S"
                }
             ],
             $position: 0
          }
       }
    })
    

    the $position specify where the element will be inserted.