I have a problem while updating an array.
sample document :
_id:11,
marksObtained:[{physics:10}, {chemistry:12}, {maths: 11}, {biology:9}, {social:9}]
name:"Someone"
field to update is:
[{chemistry:13},{zoology:12}]
So the new document looks like:
_id:11,
marksObtained:[{physics:10}, {chemistry:13}, {maths: 11}, {biology:9}, {social:9},{zoology:12}]
name:"Someone"
marks in chemistry is updated to 13 and rest values are kept as it is
I have tried $push, $addToSet, update, updateOne,updateMany
I want to avoid writing code that iterates and compare labels.
Key and value are coming from device which are dynamic, so i want to update the keys which are already present in array and if new key comes it must appended in the array
2
Answers
This is actually a pain. But there are a few options:
1 – Bulk operation
Your actions are count be simply a
$pull
(to remove the existing value from the array, IF it exist) and$push
(add the correct value). You could do this through the bulk operations api to ensure that the writes are as atomic as possible:eg: Dynamically in code:
2 – Custom
$function
to run javascript to set the valuesAs per this playground: https://mongoplayground.net/p/PcV6dMoyJ6Y.
You can set a custom javascript function to do the dirty work for you.
Annoyingly in playground, it doesn’t format very well, hence it being on a single line, but an example is this:
Where the function is:
Obviously you’ll have to set the values as per a single object as I’ve done, but you adjust as you wish.
Note: It would be a lot easier if you either formatted your
marksObtained
as:or
Having an array with a single object doesn’t really make sense.
It can be done in one update query.
If the order of the items in the array is important, it is a bit clumsy. Otherwise it can be elegant:
order of the items is important:
See how it works on the playground example
order of the items is NOT important:
See how it works on the playground example