【发布时间】:2022-01-04 15:58:13
【问题描述】:
我有一份格式如下的文件:
// Document
{
_id: ObjectId("67dc90594947be000838f7a7"),
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
}
]
},
]
}
我需要一个查询,如果就业的employmentId 匹配,则更新persons 内的现有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
{
_id: ObjectId("67dc90594947be000838f7a7"),
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
}
]
},
]
}
案例二:推新就业
// 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
{
_id: ObjectId("67dc90594947be000838f7a7"),
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
}
]
},
]
}
对于非嵌套数组,我得到了this answer。
【问题讨论】:
标签: node.js arrays mongodb mongodb-query aggregation-framework