Reputation: 6835
Trying to insert my first piece of data that looks like this:
{
"city": "Oakland",
"latitude": "37.800427",
"longitude": "-122.275880",
"state": "California",
"zipcode": "94607"
}
And when I call:
def establish_client(self):
self.client = MongoClient('localhost', 27017)
self.db = self.client['props']
def insert_mongo(self,property_arg):
props = self.db.props
props.insert(property_arg) #err line
I get the following error message:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_comm.py", line 930, in doIt
result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_vars.py", line 239, in evaluateExpression
Exec(expression, updated_globals, frame.f_locals)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_exec.py", line 3, in Exec
exec exp in global_vars, local_vars
File "<string>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 409, in insert
gen(), check_keys, self.uuid_subtype, client)
File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 386, in gen
doc['_id'] = ObjectId()
TypeError: 'str' object does not support item assignment
What gives?
My object that i am inserting is generated by the following function embedded in the class itself:
def to_JSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
Upvotes: 1
Views: 271
Reputation: 473763
You don't need to dump the dictionary into JSON string, just pass the dictionary itself to insert()
.
Quote from the tutorial that should clear things up:
Data in MongoDB is represented (and stored) using JSON-style documents. In PyMongo we use dictionaries to represent documents.
Upvotes: 3