Monday, September 2, 2013

MongoEngine - An example to get started

To get started with mongoengine for manipulating mongodb using python, you can try this super basic example:


1. Install mongodbhttp://docs.mongodb.org/manual/installation/

2. Create an isolated python environment with virtualenv:

$ virtualenv /home/.venv/example
$ source /home/.venv/example/bin/activate

3. Install mongoengine inside the virtual environment:

(example) trinh@trinh-pc$ pip install mongoengine

4. Run python command to enter the console >> connect to a db >> define some models >> and create instances using mongoengine api:

$ python
>>> from mongoengine import *
>>> connect('test')
MongoClient('localhost', 27017)
>>> class User(Document):
. . .         name = StringField()
. . .
>>> class Post(Document):
. . .         content = StringField()
. . .         author = ReferenceField(User)
>>> my_user = User(name="Trinh Nguyen")
>>> my_user.save()
<User: User object>
>>> new_post = Post(content="This is a test post.")
>>> new_post.author = my_user
>>> new_post.save()
<Post: Post object>
>>> new_post.content
u'This is a test post.'
>>> my_user.name
u'Trinh Nguyen'
>>> new_post.author
<User: User object>
>>> new_post.author.name
u'Trinh Nguyen'


Look like Django's ORM huh? :D

Reference: http://docs.mongoengine.org/en/latest/guide/defining-documents.html