0

I am using pymongo for programming. I want to update a field from an embedded document from an array which is stored in the MongoDB database. I can update it directly from the mongo shell by using the dot (.) operator like

Ex:

db.coll.update({},{"year.0.month":5})

But if I use the same year.0.month in pymongo, I am unable to update it as it giving me an error.

Can someone please elaborate how can I achieve this in pymongo?

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84

1 Answers1

0

Use $set to update. e.g

db.coll.update({},{ "$set": {"year.0.month":5}}))

By the way from version 3 update() is depricated, So for update single document use update_one or find_one_and_update() e.g

db.coll.update_one({},{ "$set": {"year.0.month":5}})

or

db.coll.update_one_and_update({},{ "$set": {"year.0.month":5}})

And for update many doc use update_many() e.g

db.coll.update_many({},{ "$set": {"year.0.month":5}},multi=True)
Osman Goni Nahid
  • 1,193
  • 2
  • 15
  • 24
  • Hi, Thank you for your answer. the issue is, pymongo is not accepting "year.0.month" format. Do yo know its equivalent syntax for pymongo? – Rupashri Patil Sep 22 '18 at 10:07
  • could you please show me your sample doc @RupashriPatil – Osman Goni Nahid Sep 22 '18 at 10:13
  • But above one should work did you get any error then show me or you can check this answer [link](https://stackoverflow.com/questions/11372065/mongodb-how-do-i-update-a-single-subelement-in-an-array-referenced-by-the-inde) – Osman Goni Nahid Sep 22 '18 at 10:18
  • This is the similar one which i am trying. Error is: WriteError(u'cannot use the part (comments of comments.comment_ordinal.num_likes) to traverse the element ({comments: [ { author: "Tonia Surace", body: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ...", email: "DcwPJgyw@mCBzxAfy.com", num_likes: 1 }]) – Rupashri Patil Sep 22 '18 at 10:26
  • Try to use positional operator `$` the. Do you want to push a new element into the array? then you should use `$push`. – Osman Goni Nahid Sep 22 '18 at 10:33
  • you are making mistake elsewhere – Osman Goni Nahid Sep 22 '18 at 16:36