我有MongoDB集合,文档如下:
{"name": "person1", "parents": [
{"relationship": "father", "name": "father1", "age": 40},
{"relationship": "mother", "name": "mother1", "age": 42}
]}
{"name": "person2", "parents": [
{"relationship": "father", "name": "father2", "age": 50},
{"relationship": "mother", "name": "mother2", "age": 45}
]}
我正在try 将文档展平,如下所示:
{"name": "person1", "father_name": "father1", "father_age": 40, "mother_name": "mother1", "mother_age": 42}
{"name": "person2", "father_name": "father2", "father_age": 50, "mother_name": "mother2", "mother_age": 45}
基本上,我希望从parents个数组的每个元素(对象)中获取某些字段,并将它们作为输出文档中的新字段.我怎样才能做到这一点呢?
我编写了如下聚合管道:
[
{
$project: {
_id: 0,
name: 1,
father_name: {
$cond: {
if: {
$eq: ["$parents.relationship", "father"],
},
then: "$parents.name",
else: null,
},
},
father_age: {
$cond: {
if: {
$eq: ["$parents.relationship", "father"],
},
then: "$parents.age",
else: null,
},
},
mother_name: {
$cond: {
if: {
$eq: ["$parents.relationship", "mother"],
},
then: "$parents.name",
else: null,
},
},
mother_age: {
$cond: {
if: {
$eq: ["$parents.relationship", "mother"],
},
then: "$parents.age",
else: null,
},
},
},
},
]
但它的输出如下所示,并不像预期的那样:
{
"name": "person1",
"father_name": null,
"father_age": null,
"mother_name": null,
"mother_age": null
}