Inserting JSON directly into MongoDB?

8,826 views
Skip to first unread message

x0ne

unread,
Jan 1, 2011, 11:15:09 PM1/1/11
to mongodb-user
I am new to MongoDB and the documentation is great, but for whatever
reason I can't find someone who has the same problem I do. Basically
what I want to do is take a JSON object and just insert it into Mongo.
Here is the example I am trying:

iimport pymongo
import json
from pymongo import Connection

connection = Connection('localhost', 27017)
db = connection.test_database
collection = db.test_collection

post = {"author": "Mike"} #{'author': 'Mike'}
post_json = json.dumps(post) #{"author": "Mike"}
post_json_c = post_json.replace("\"", "'") #{'author': 'Mike'}

collection.insert(post) #works
#collection.insert(post_json) #fails
collection.insert(post_json_c) #fails

I saw documentation (http://api.mongodb.org/python/1.9%2B/api/bson/
json_util.html) about a json_utils tool in the bson module, but the
documentation doesn't really help me too much with the usage. Any help
is greatly appreciated.

Eliot Horowitz

unread,
Jan 1, 2011, 11:23:57 PM1/1/11
to mongod...@googlegroups.com
You can't insert JSON directly, you have to insert a python dict or a
BSON object.

>>> import pymongo
>>> import json
>>> connection = pymongo.Connection()
>>> coll = connection.test.pyfoo
>>> s = "{ \"name\": \"eliot\" }"
>>> coll.insert( json.loads( s ) )
ObjectId('4d1ffda57dc7a6fb63000000')
>>> coll.find_one()
{u'_id': ObjectId('4d1ffda57dc7a6fb63000000'), u'name': u'eliot'}
>>>

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

x0ne

unread,
Jan 1, 2011, 11:33:24 PM1/1/11
to mongodb-user
Gah, I am dumb. I can't believe I forgot all about the json.loads
method. Thanks a lot!
Reply all
Reply to author
Forward
0 new messages