Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert python object in mongodb

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!

like image 848
helpmelearn Avatar asked Apr 24 '12 05:04

helpmelearn


People also ask

Can MongoDB store Python objects?

An introduction to MongoDB with PyMongo MongoDB is a document based database with a dynamic data schema. The JavaScript Object Notation (JSON) that it supports is a natural fit for working with objects in modern programming languages like JavaScript, Python and others.

Can I use Python in MongoDB?

Python can be used in database applications. One of the most popular NoSQL database is MongoDB.

How do you insert using PyMongo?

To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method. The first parameter of the insert_one() method is a dictionary containing the name(s) and value(s) of each field in the document you want to insert.


1 Answers

What is value in your initial code?

It should be dict not class instance

This should work:

postings.insert(posting.__dict__)
like image 200
San4ez Avatar answered Sep 19 '22 13:09

San4ez