Update single (same) field in every object of an array

Received assistance on Stack Overflow. Providing the final working syntax for future use:

function setRoundScores($roundId, $scoresArray) {
    	
    $client = new MongoDB\Client($_ENV['MDB_CLIENT']);

	$collection = $client->golf->round;

    $match = [ '_id' => new MongoDB\BSON\ObjectID( $roundId ) ];
    	
    $set = [
    	'$set' => [
    		'holes' => [
    			'$map' => [
    				'input' => [
    					'$range' => [ 0, [ '$size' => '$holes']]
    				],
					'in' => [
						'$mergeObjects' => [
							[ '$arrayElemAt' => [ '$holes', '$$this' ]],
							[ 'holeGross' => [ '$toInt' => [ '$arrayElemAt' => [ $scoresArray, '$$this' ]]]]
						]
					]
    					
    			]
    		]
    	]
    ];
    	
    $updateOne = $collection->updateOne($match, [$set]);
    	
	return $updateOne->getModifiedCount();
		
}

It was the number of square braces in the 'holeGross' => line. I also had to add an extra layer to this, '$toInt', as passing the var’s using $_POST converted them to strings.

1 Like