MongoDB ORM for Python?


Question

I am trying to migrate from sqlalchemy(SQlite) to using mongodb. I would like schema vertification. I amm looking at mongokit, but I want something which is similar to mappers, so that it would save from the object's property, and not a dict.

i would like a mapper so that i can use existing objects without modifying them.

1
82
8/28/2019 8:11:46 AM

Accepted Answer

Another option is MongoEngine. The ORM for MongoEngine is very similar to the ORM used by Django.

Example (from the tutorial):

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()
66
6/7/2012 2:04:08 PM

Not being satisfied with either MongoKit or MongoEngine, I decided to write my own object-oriented interface for Python.

I delegated all queries directly to pymongo, so the query syntax there is the same. Mostly, it's just an object-wrapper around the results, with some other helpers like database connection pooling, DBRef support, and other convenience methods to make your life easier.

It's called Minimongo and it's available from github. Happy hacking!

Example:

from minimongo import Model, MongoCollection 

class MyObject(Model): 
    model = MongoCollection(database='test', collection='my_collection')

m = MyObject()
m.x = 1
m.field = 'value'
m.other = {'list': True}
m.save()

x = MyObject({'x': 1, 'y': 2}).save()

objs = MyObject.find({'x': 1})
for o in objs: 
    print o

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon