I've got a document in MongoDB like this:
{
"name": "wine",
"foodstuffSelectedPortions": {
"id_1": [
{
"foodstuffId": "f1",
"portion": {
"portionName": "portion name 1",
"portionWeight": {
"value": 1,
"unit": "KG"
}
}
},
{
"foodstuffId": "f2",
"portion": {
"portionName": "portion name 2",
"portionWeight": {
"value": 100,
"unit": "ML"
}
}
}
],
"id_2": [
{
"foodstuffId": "f3",
"portion": {
"portionName": "portion name 3",
"portionWeight": {
"value": 15,
"unit": "ML"
}
}
}
]
}
}
and I want to update foodstuffSelectedPortions.portion object into array that contains this object. So the expected result should look like this:
{
"name": "wine",
"foodstuffSelectedPortions": {
"id_1": [
{
"foodstuffId": "f1",
"portion": [
{
"portionName": "portion name 1",
"portionWeight": {
"value": 1,
"unit": "KG"
}
}
]
},
{
"foodstuffId": "f2",
"portion": [
{
"portionName": "portion name 2",
"portionWeight": {
"value": 100,
"unit": "ML"
}
}
]
}
],
"id_2": [
{
"foodstuffId": "f3",
"portion": [
{
"portionName": "portion name 3",
"portionWeight": {
"value": 15,
"unit": "ML"
}
}
]
}
]
}
}
I've tried this query:
db.foodstuff.update(
{ },
{ $set: { "foodstuffSelectedPortions.$[].portion": ["$foodstuffSelectedPortions.$[].portion"] } }
)
but it gives me an error: Cannot apply array updates to non-array element foodstuffSelectedPortions: which looks fine because the foodstuffSelectedPortions is an object not array.
How to write this query correctly? I use MongoDB 4.4.4 and Mongo Shell.