MongoDB.live, free & fully virtual. Register Now MongoDB.live, free & fully virtual. Register Now

Update pipeline: Push into middle of array

I would like to add an item to the middle of an array during the aggregation pipeline.

The solution to the question below shows adding to the end of an array using ‘$concatArrays’, but I would like to add to the middle using something like ‘$position’.

Does anyone know if ‘$push’ will get added as an update operation during the aggregation pipeline?
https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/

Would really appreciate the help!

Hello @Scott_Wager ,

You can use the $concatArrays in your case also. For example, consider a document:

{ arr: [ 8, 39, 21, 0, 999 ] }

and you want to insert a number 555 as third element (after the 39) of the array field arr.

{ 
    $set: { 
        arr: { 
           $concatArrays: [ 
               { $slice: [ "$arr", 2 ] }, 
               [ 555 ], 
               { $slice: [ "$arr", -3 ] } 
           ] 
        } 
    } 
}

The result : { arr: [ 8, 39, 555, 21, 0, 999 ] }

3 Likes

This blew my mind, I would never have thought of doing that.

I have a recursive data structure that will get big (similar to a file system with folders), so I would prefer to have an option to push into the array. I’m reluctant to reset the entire field as there could be a lot of data to write. Do you know if there is or ever will be a mutable solution like push?

I’ve gone through so much stackoverflow this was really my last shot, so if this is the only option then I’ll stick with it. Thank you so much for the quick reply!