Krypto456
Krypto456

Reputation: 49

How to update MongoDb document using python

I have 2 documents in a collection with a structure like below. I want to update "Source" as Home where environment is "QA" and Name is "Alan".

{
  environment: DevA,
  data: [
   { 
     Name: "John",
     Source: "Home"
   },
   { 
     Name: "Alan",
     Source: "Office"
   },
   { 
     Name: "Susan",
     Source: "Office"
   }
  ],
},
{
  environment: DevB,
  data: [
   { 
     Name: "John",
     Source: "Home"
   },
   { 
     Name: "Alan",
     Source: "Office"
   },
   { 
     Name: "Susan",
     Source: "Office"
   }
  ],
}

I tried the following code below. But it did not update it, neither gave an error.

 collection1.update_one({ 'environment':'QA', 'data.Name':'Alan'},
                          { $'set': {
                                     "data":"Source":"NewValue"
                                    }
                          })

Upvotes: 0

Views: 564

Answers (1)

Krypto456
Krypto456

Reputation: 49

I was able to update it using following code:

collection1.update_one( 
{
  "environment":"DevB",
  "data" {"$elemMatch": { "Name": "Alan"} }
},
{
  "$set" : {
          "data.$.source":"ABC"
           }   
 })

Upvotes: 1

Related Questions