Does anyone know how to add an array element to a mongodb array and set a "virtual" order to the size of the array, all in an atomic operation?
So, something like:
db.users.updateOne(
{ _id: 1},
{ $addToSet: { images: {name: 'new image', order: "size of the array"} } }
)
The idea is to always have the last array element added have an order that is last.
Update:
Data before op:
{
_id: 1,
images: [
{ name: 'some name', order: 0 }
]
}
Data after op:
{
_id: 1,
images: [
{ name: 'some name', order: 0 },
{ name: 'new image', order: 1 }
]
}
Update 2:
In case anyone is interested, to update the order atomically, you can do something like this (build this dynamically, of course):
db.collection.update({
_id: 1
},
{
$set: {
"images.$[elem].order": 4,
"images.$[elem2].order": 3
}
},
{
arrayFilters: [
{
"elem.name": {
$eq: "some name"
}
},
{
"elem2.name": {
$eq: "new image"
}
}
]
})
Thank you!