How to update array by index in aggregation?

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?

One way is to use $concatArrays with 2 $slice-s…

Try the following:

index = 1
slice_before_index = { $slice : [ "$daysConsume" , 0 , index ] }
slice_after_index = { $slice : [ "$daysConsume" , index + 1 , 31 ] }
concat_arrays = { $concatArrays : [ slice_before_index , [ "$inventory" ] , slice_after_index ] }
db.ingredient.update( query , [ { $set : { daysConsume : concat_array } } ] )

You might need to adjust the values in the slice_… with + or - 1 to get exactly what you need. Your sample document started with all 0s so I am not too sure of which 0 I lose or gain.

After some test, it look like slice_after_index needs to be

slice_after_index = { $slice : [ "$daysConsume" , index , 31 ] }

The +1 is removed compared to the original.