I have the following document structure. I am trying to update specific values inside the holes
sub-array:
Each Array
element is an Object
representing the score on a golf hole, with various properties (fields). I am trying to provide the ability to update the holeGross
field ONLY for each score. On my PHP website, this is using a POST form, which pushes an Array of scores and the round._id
value too, as:
Array ( [holeScoreHidden] => Array ( [1] => 7 [2] => 7 [3] => 7 [4] => 8 [5] => 7 [6] => 7 [7] => 7 [8] => 7 [9] => 7 ) [roundId] => 60c642db09080f1b50331b2d [submit] => )
However, initially I am trying to get it working with MongoDB shell syntax. I have tried following the findAndModify()
method in the MongoDB shell, which updates 1 field specified, i.e. where hole.no
== 1:
db.roundTest.findAndModify({
query: { _id : ObjectId('60c916684bd16901f36efb3a') },
update: { $set: { "holes.$[elem].holeGross" : 8 } },
arrayFilters: [ { "elem.no": 1 } ]
})
How can I update all Array
elements in this document? Each holeGross to be updated will [likely] be different, so need to match the hole.no
(âelem.noâ) against the corresponding new score.
I expect I will need to also perform a loop, in order to go through the $_POST array. Would this likely be to form echo
statements, or can it be directly integrated into the findAndReplace
call?
Also, can I perform this within a single method call, or would this approach require a call per single field / document that is to be updated? I would prefer a single call, obviously.
The documentation says that arrayFilters
is:
arrayFilters: [ <filterdocument1>, ... ]
But I donât want to pass in a whole document.