简体   繁体   中英

mongodb update item in an object isnt working as expected

I am using python with mongodb in the backend. my data looks like that:

data = {"_id": ObjectId("anything", "x": {"one": "number", "two": "number"})}

I am trying to update all values in x that meet a certain condition. Here is what i am trying:

col.update( {"x.one": "number"}, {"$set": {"x.onnneeee": "number"}}, multi=True)
col.update_many( {"x.one": "number"}, {"$set": {"x.onnneeee": "number"}})

However, After checking the database. I see the new value is being added to the end of the "x" object while the object {"x.one": "number"} isnt being changed. any explanation why this is happening?

Use $unset in the same update dict to unset x.one

col.update( {"x.one": "number"}, {"$set": {"x.onnneeee": "number"}, "$unset": {"x.one": ""}}, multi=True)

The first arg {"x.one": "number"} is just a filter query and identifies records which are to be updated. The 2nd arg sets what updates to perform on the selected records

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM