Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Mongo Document with Pymongo

I want to update an existing mongodb document by its ID with pymongo(version 3.0.3). However nothing gets updated with my python code. Does anyone know why..?

Here is the mongodb script I want to run and this works fine from a mongo client, Robomongo.

db.mycollection.update(
  { '_id': ObjectId("55d49338b9796c337c894df3") },
  { $set: { "details.model": "14Q22" } },
  upsert=false
  )

However this python code does not work.

client = pymongo.MongoClient("1.1.1.1", 27017)
db = client.mydb

db.mycollection.update(
  { '_id': "55d49338b9796c337c894df3" },
  { '$set': { "details.model": "14Q22" } },
  upsert=False
  )

It returns

{u'n': 0, u'nModified': 0, u'ok': 1, 'updatedExisting': False}
like image 353
E.K. Avatar asked Dec 08 '22 01:12

E.K.


1 Answers

Yes, you have to specify an ObjectId instance as follows:

from bson.objectid import ObjectId
db.mycollection.update({'_id': ObjectId("55d49338b9796c337c894df3")},  {'$set': {"details.model": "14Q22"}}) 
  • also notice that mycollection.update, although it works, is deprecated due to introduction of new CRUD operations, better use mycollection.update_one or mycollection.find_one_and_update
like image 80
nickmilon Avatar answered Dec 30 '22 10:12

nickmilon