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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With