Search code examples
pythonmongodbmongodb-querypymongo

How can I update a specific field of a document, one by one, while iterating over all the documents?


I have documents in a collection, and each document is (say) like this:

doc: {
'dflag':0
'name':
'address':
}

While iterating over, that is:

query = {"dflag":0}
for doc in mydb["mycol"].find(query):
    -do-something-
    ...
    # want to change 'dflag' of this particular doc, from 0 to 1
    newvalue = { "$set": { "dflag": 1 } }
    doc.update(newvalue)

I want to update 'dflag' of each document one by one, but, doing it like above is not working. How can I update a specific field of a document, one by one, while iterating over all the documents?


Solution

  • You can do it with update method

    doc.update(query, newvalue)
    

    Also, you can use update_one to update the first element that matched the query.

    one.update_one(query, newvalue)