8

Folks, I just spent a good amount of time trying to look this up -- I ought to be missing something basic.

I have a python object, all I want to do is to insert this object in mondodb.

This is what I have:

from pymongo import Connection
import json

conn = Connection()
db = conn.cl_database
postings = db.postings_collection

class Posting(object):
    def __init__(self, link, found=None, expired=None):
        self.link = link
        self.found = found
        self.expired = expired

posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
postings.insert(value)

throws this error:

Traceback (most recent call last):
  File "./mongotry.py", line 21, in <module>
postings.insert(value)
  File "build/bdist.macosx-10.7-intel/egg/pymongo/collection.py", line 302, in insert
  File "build/bdist.macosx-10.7-intel/egg/pymongo/database.py", line 252, in _fix_incoming
  File "build/bdist.macosx-10.7-intel/egg/pymongo/son_manipulator.py", line 73, in transform_incoming
TypeError: 'str' object does not support item assignment

Seems like it is because json.dumps() returns a string.

Now if I do do a loads of the value before inserting it works fine:

posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
value = json.loads(value)
postings.insert(value)

What is the most straight-forward to do this?

Thanks!

2 Answers 2

17

What is value in your initial code?

It should be dict not class instance

This should work:

postings.insert(posting.__dict__)
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I realized I missed a line there, just edited the question.
Jeez, that's right. Thanks, feel stupid to have missed something so silly.
3

You are misusing the insert method for the collection. Review here: http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert

What you need to be inserting is a document. It should be a dict with keys and values. Simply trying to insert a string is not appropriate. json.dumps returns a string in json format. If you are just dumping it to get a dict then the json step is not necessary.

Insert exactly how your documents should look:

postings.insert({"key":"value"})

Or convert your class instance directly into the dict you want to store as a doc and then insert it. It works with your json.dumps.loads() because that ultimately does give you a dict.

1 Comment

How to insert leaving outer of nested dictionary here in this question?stackoverflow.com/questions/59499237/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.