Tony Roczz
Tony Roczz

Reputation: 2398

How to update mongodb array values

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.

Upvotes: 1

Views: 90

Answers (2)

Suhas Shelar
Suhas Shelar

Reputation: 983

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}})

Upvotes: 1

chridam
chridam

Reputation: 103305

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}})

Upvotes: 1

Related Questions