I have a document in following format:
// Document
{
persons: [
{
personId: "61cd90594947be000838f7c1",
name: "John Doe"
employment: [
{
employmentId: "61cd9059494abe000838f7c8",
type: "Full time",
salary: 1010101
}
]
},
{
personId: "61cd90594947be000838f7c2",
name: "Jane Austin"
employment: [
{
employmentId: "61cd9059494abe000838f7c8",
type: "Part time",
salary: 11011111
}
]
},
]
}
I need a single query which either updates existing employment
inside persons
if the employmentId
of employment matches or push new element to the array.
e.g.
Case I: Update employment
// update payload
// This employment id is the first employment of John Doe
// So the first employment will be updated
{
personId: "61cd90594947be000838f7c1",
employmentId: "61cd9059494abe000838f7c8",
frequency: "weekly"
}
// The updated document
{
persons: [
{
personId: "61cd90594947be000838f7c1",
name: "John Doe"
employment: [
// This is updated employment
{
employmentId: "61cd9059494abe000838f7c8",
type: "Full time",
salary: 1010101,
frequency: "weekly"
}
]
},
{
personId: "61cd90594947be000838f7c2",
name: "Jane Austin"
employment: [
{
employmentId: "61cd9059494abe000838f7c8",
type: "Part time",
salary: 11011111
}
]
},
]
}
Case II: Push new employment to array
// update payload
// This employment id is not in John Doe
// So the data will be pushed to array
{
personId: "61cd90594947be000838f7c1",
employmentId: "61cd9059494abe000738f7c1",
frequency: "weekly"
}
// The updated document
{
persons: [
{
personId: "61cd90594947be000838f7c1",
name: "John Doe"
employment: [
{
employmentId: "61cd9059494abe000838f7c8",
type: "Full time",
salary: 1010101
},
/// This is newly added employment
{
employmentId: "61cd9059494abe000738f7c1",
frequency: "weekly"
}
]
},
{
personId: "61cd90594947be000838f7c2",
name: "Jane Austin"
employment: [
{
employmentId: "61cd9059494abe000838f7c8",
type: "Part time",
salary: 11011111
}
]
},
]
}
For a non-nested array I was given this answer.