I’m retrieving a document like this:
user = db.users.find_one( { '_id' : ObjectId( 'anID' ) } )
But I can’t figure out how to update the document if I want to change the value of ‘gender’. This doesn’t work:
newValue = {
'gender' : gender
}
db.users.update( user, newValue, False )
Is my syntax wrong? What’s the best way to update user
Your update syntax is not correct, it should be:
Where
specis the same filter that you used for the find, i.e.{ '_id' : ObjectId( 'anID' ) }You can either update the document by replacing it with a modified document or use a targeted update to change only a certain value. The advantage of the targeted update is that it saves you the first round trip to the server to get the user document.
Replacement update:
Targeted update: