Следующий запрос может дать нам ожидаемый результат:
db.collection.aggregate([
{
$addFields:{
"optionLevel":{
$map:{
"input":"$optionLevel",
"as":"info",
"in":{
$mergeObjects:[
"$$info",
{
"deparmentId":{
$ifNull:["$$info.deparmentId",""]
}
}
]
}
}
}
}
}
]).pretty()
Набор данных:
{
"_id" : ObjectId("5d89ccf8c3c948ac48e449fc"),
"id" : 1,
"name" : "option 1",
"optionLevel" : [
{
"id" : 1,
"deparmentId" : null,
"name" : "level 1"
},
{
"id" : 2,
"deparmentId" : null,
"name" : "level 2"
}
]
}
Выход:
{
"_id" : ObjectId("5d89ccf8c3c948ac48e449fc"),
"id" : 1,
"name" : "option 1",
"optionLevel" : [
{
"id" : 1,
"deparmentId" : "",
"name" : "level 1"
},
{
"id" : 2,
"deparmentId" : "",
"name" : "level 2"
}
]
}