My collection is named ingredient, its document data looks like this:
db.ingredient.insertMany(
[{
name: "sugar",
inventory: 100,
daysConsume: [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
},
{
name: "salt",
inventory: 230,
daysConsume: [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
}]
);
now I want to set the daysConsume array of index 1 to the value of field inventory, I use script as this:
db.ingredient.updateOne({_id: ObjectId("63d27f53cc3fa8ed2594a6ee")},[{$set:{"daysConsume.1":"$inventory"}}])
after that the document looks like this:
{
_id: ObjectId("63d27f53cc3fa8ed2594a6ee"),
name: 'salt',
inventory: 230,
daysConsume: [
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }, { '1': 230 }, { '1': 230 },
{ '1': 230 }
]
}
every item of the array was updated, this is not what I expected,
I just want to update the item of index 1, as below:
{
_id: ObjectId("63d27f53cc3fa8ed2594a6ee"),
name: "salt",
inventory: 230,
daysConsume: [
0, 230, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
}
How can I only update the value of index 1?