0

I am trying to update a sub-document which is an array in mongodb using array index. Below is my code, is this possible ? or is their any othr way

arrayindex = 3;
Model.update({_id: ObjectId(id), 'array.userid' : ObjectId(userid)},{$set:{"array.arrayindex.points" :20,  }}

i want to update 3rd object in subdocument.

Note : Above code is not working and when i use $ operator it updates only first matched object in array also arrayindex variable can be any value dynamically known

Gaurav Kumar
  • 698
  • 1
  • 8
  • 15
  • ``{ $set: { [`array.${arrayindex}.points`]: 20 } }`` in modern JavaScript distributions. All other variations in the marked duplicate. – Neil Lunn Apr 30 '18 at 00:27
  • Also, really bad idea. You should instead be using the actual ["positional `$` operator"](https://docs.mongodb.com/manual/reference/operator/update/positional/) and not a **fixed array index**. Presuming that an array is unmodified since your last read of the data so the index has not changed is certain to lead to problems. – Neil Lunn Apr 30 '18 at 00:31
  • Well i achieved what i wanted in another way using Mongo Aggregation Framework, Thanks for suggestion. will post solution here later as an answer – Gaurav Kumar Apr 30 '18 at 07:18
  • The aggregation framework **does not update** documents. So it would be really difficult to get a solution that way. Also, this question is closed so you cannot post a solution here. The solution is what you have been pointed to. – Neil Lunn Apr 30 '18 at 07:21
  • ok , yes aggregation framework doesn't update , but have done it a two step process , query by aggregation framework and normal update in its callback sub-documents individually. – Gaurav Kumar Apr 30 '18 at 07:51

0 Answers0