I have an address
field value inside basicDetails
. I want that value to bring to the root field by adding a new field named address
, so I am trying this way to add a new field address in all the documents. But the issue is the value is unable to update. I think I am wrong in syntax for referencing the value properly. Please help me. Thanks in advance.
Updation Query:
db.businesslistings.updateMany({},
{$set: {"address": '$attributes[0].basicDetails[1].valueString'}})
Result:
address: "$attributes[0].basicDetails[1].valueString"
The simple update query cannot do complex queries such as getting the field value. You need the update query with aggregation pipeline.
The dot notation (path) doesn't work, you need the query as below:
From inner to outer
Get the first element of the attributes
array.
Get the basicDetails
field.
Get the second element of the basicDetails
array.
Get the valueString
field.
db.businesslistings.updateMany({},
[
{
$set: {
"address": {
$getField: {
input: {
$arrayElemAt: [
{
$getField: {
input: {
$arrayElemAt: [
"$attributes",
0
]
},
field: "basicDetails"
}
},
1
]
},
field: "valueString"
}
}
}
}
])