1

I have a document stored in mongodb like this

"Fiction" : [
           {
                   "SNo": "1",
                   "authorName" : "Enid Blyton",
                   "bookName" : "Secret series",
                   "Amount" : 115
           },
           {
                   "SNo": "2",
                   "authorName" : "Enid Blyton",
                   "bookName" : "Mystery series",
                   "Amount" : 150
           }
   ]

I would like to update the amount from 115 to 135.

I tried to update the value like this.

db.fiction.update({"Fiction.SNo":"1"},{$set:{"Fiction.Amount":135}})

But I get a error.

The error is

cannot use the part (Fiction of Fiction.Amount) to traverse the element 

Can anyone help on this, I need to implement this to work from python.

Tony Roczz
  • 2,366
  • 6
  • 32
  • 59

2 Answers2

1

Use the $ positional operator in your update as this identifies the element in an array to update without explicitly specifying the its position in the array:

db.fiction.update({"Fiction.SNo":"1"},{$set:{"Fiction.$.Amount":135}})
chridam
  • 100,957
  • 23
  • 236
  • 235
1

The $ operator is used to iterate through the array list while updating.

Your query would be : db.Fiction.update({"Fiction.SNo":"1"},{$set:{"Fiction.$.Amount" : 135}})

Suhas Shelar
  • 963
  • 2
  • 10
  • 23