Home > Mobile >  Updating nested MongoDB collection (Pymongo)
Updating nested MongoDB collection (Pymongo)

Time:10-19

-EDIT-

How can I update a nested collection using Pymongo based on more than 1 condition?

My document looks like this:

[{'_id': ObjectId('613eb154aee899694f934259'),
  'company': 
      [{'name': 'Flower shop', 
        'persons': 
            [{'personId': '1000',
              'personIdType': 'Passport/Others'},
             {'personId': '3000',
              'personIdType': 'Passport/Others'}
            ]}
      ]}
]

I want to update the personId 1000 to 2000. Therefore the 2 conditions are: objectId = '613eb154aee899694f934259' AND the personId = 1000

I appreciate any help.

CodePudding user response:

Try to use $set to set the personId field. You will need arrayFilter to specifiy the filtering condition for the array.

db.collection.update({
  _id: ObjectId("613eb154aee899694f934259")
},
{
  $set: {
    "company.$[].persons.$[p].personId": 2000
  }
},
{
  arrayFilters: [
    {
      "p.personId": "1000"
    }
  ]
})

Here is the Mongo playground for your reference.

CodePudding user response:

@ray's answer is correct. But you have to convert his solution to python.

Below answer is the exact replication of @ray answer converted in python.

from pymongo import MongoClient
from bson.objectid import ObjectId


col = MongoClient()["temp"]["tmp9"]

col.update_many({
  "_id": ObjectId("613eb154aee899694f934259"),
}, {
  "$set": {
    "company.$[].persons.$[p].personId": "2000",
  }
},
  array_filters=[{"p.personId": "1000"}]
)
  • Related