I need to move an array element from one array to another array within the same document and delete the element from the original array it was moved from.
// Document
{
persons: [
{
personId: "61cd90594947be000838f7c1",
name: "John Doe"
employment: [
{
type: "Full time",
salary: 1010101
}
]
},
{
personId: "61cd90594947be000838f7c2",
name: "Jane Austin"
employment: [
{
type: "Part time",
salary: 11011111
}
]
},
]
}
I need to move one of the employment element from John Doe to Jane Austin and both of those persons are in the same document. And I need to delete that moved element from John Doe.
I tried using update pipeline but to no avail.
db.personCollection.updateOne(
{ _id: ObjectId("61cd90594947be000838f7c8") },
[
{
"$project": {
"dataToMove": {
"$ifNull": [
{
"$arrayElemAt": [
{
"$slice": [
{
"$map": {
"input": {
"$slice": [ "$persons", 0, 1 ]
},
"as": "el",
"in": "$$el.employment"
}
},
0, 1
]
},
0
]
},
"*"
]
}
}
},
{
$set: {
[`persons.1.employment`] : {
$concatArrays: [
"$persons.1.employment",
"$dataToMove"
]
}
}
},
{
$pull: {
[`persons.1.employment`]: {
$elemMatch: "$dataToMove"
}
}
}
]
);