Domanda

I try to perform a simple update but data is not updated in the db. In the following code snippet, I am:

  1. creating a new account and inserting it into the db (success),
  2. retrieving it (success),
  3. updating it (fail)

It is all done at localhost, default instance, no replica involved. I followed documentation step by step, yet, can't figure out what am I doing wrong.

from pymongo import Connection
from pymongo.objectid import ObjectId

def _byid(id):
    return ObjectId(id)

class Account(object):
    collection = Connection().testdb.accounts

    def insert(self, data):
        return self.collection.insert(data)

    def byid(self, id):
        return self.collection.find({"_id": _byid(id)})

    def update(self, id, data):
        return self.collection.update({"_id": _byid(id)}, {"$set":  data})

acc_data = {
    "contact_name": "Mr. X",
    "company_name": "Awesome Inc.",
}

account = Account()

# INSERT
_id = account.insert(acc_data)
print 'ID:', _id

# RETRIVE
for ac in account.byid(_id):    
    print ac["company_name"]

# UPDATE
acc_data["company_name"] = acc_data["company_name"][::-1].upper()
print account.update(_id, acc_data)

# RETRIVE AGAIN
for ac in account.byid(_id):    
    print ac["company_name"]
È stato utile?

Soluzione

Got it. Update should be:

def update(self, id, data):
    return self.collection.update({"_id": _byid(id)}, data)       

No need for "$set"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top