How can I take the last element in an array and add it to an array in another field, in the same document? As below, I want to add "z" to field2.
{
field1: ["x","y","z"],
field2: []
}
You can use Updates with Aggregation Pipeline, which is available in MongoDB versions starting from MongoDB 4.2
Update Query will look something like this
db.collection.update({},[
{
$set: {
field2: {
$concatArrays: [
"$field2",
[
{
$arrayElemAt: [
"$field1",
{
$subtract: [
{
$size: "$field1"
},
1
]
}
]
}
]
]
}
}
}
])
The above query will take the last element from the field1 array and add it to the field2 array.
PS: If you just want to see the working of aggregation pipeline used in the update, you see it here
$arrayElemAt: ["$field1", { $subtract: [{ $size: "$field1" }, 1] }] you can simply use $arrayElemAt: ["$field1", -1] - or in Mongo 4.4 just $last: "$field1"