Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move an array element from one array position to another (mongo)

I have a list like this:

{ 
    arr: [
        { _id: 'a', val: 1 }, 
        { _id: 'b', val: 4 }, 
        { _id: 'd', val: 0 }, 
        { _id: 'c', val: 8 }
    ] 
}

And I need to put the element {_id: c} before the element {_id: d}. How can I do it with mongo? Of course, I can download the doc to my server, prepare it and upload the one to the mongo server. But I think, it's not a good way.

P.S: sorry, I need to move the element (push it to a new position and remove the one from old position)

like image 540
Саша Вульф Avatar asked Jan 17 '26 13:01

Саша Вульф


1 Answers

You can use the keyword $position to specify where in the array you want to insert the value. Use it when $pushing an element on and you'll be able to insert that element into a specific place in the array.

db.collection.update(
    {parameter: doc},
    {$push: {
        arr: {
            $each: [{_id: "c", val: 8}],
            $position: 2
        }
    })

This will push that object into position 2 of your array. If you're looking to manipulate the array by removing objects at specific points, you can refer to the answer I linked in the comments.

like image 110
Gibryon Bhojraj Avatar answered Jan 20 '26 04:01

Gibryon Bhojraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!