¡Esta es una revisión vieja del documento!
It's a MongoDB ORM for Python.
$ pip install mongoengine
To start using MongoEngine we will import like this:
import mongoengine
To connect a DB we will use the connect function, its first argument is the DB:
connect('project1') connect('project1', host='192.168.1.35', port=12345) connect('project1', username='webapp', password='pwd123') connect('project1', host='mongodb://localhost/database_name')
Next schema implements a Blog where a User can create different type Posts. Those types are inherited classes from Post.
class User(Document): email = StringField(required=True) first_name = StringField(max_length=50) last_name = StringField(max_length=50) class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User) meta = {'allow_inheritance': True} class TextPost(Post): content = StringField() class ImagePost(Post): image_path = StringField() class LinkPost(Post): link_url = StringField()
tags = ListField(StringField(max_length=30)), a ListField is a field object that allows to have a list of other field objects (including other lists).class Comment(EmbeddedDocument): content = StringField() name = StringField(max_length=120) class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment))
When we define a ReferenceField we can indicate reverse_delete_rule=CASCADE to delete all the objects when a referenced object is deleted (it does not work with MapFields neither DictFields).
class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User, reverse_delete_rule=CASCADE) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment))
ross = User(email='ross@example.com', first_name='Ross', last_name='Lawley').save() # this is other way to save ross ross1 = User(email='ross1@example.com') ross1.first_name = 'Ross1' ross1.last_name = 'Lawley' ross1.save() post1 = TextPost(title='Fun with MongoEngine', author=john) post1.content = 'Took a look at MongoEngine today, looks pretty cool.' post1.tags = ['mongodb', 'mongoengine'] post1.save() post2 = LinkPost(title='MongoEngine Documentation', author=ross) post2.link_url = 'http://docs.mongoengine.com/' post2.tags = ['mongoengine'] post2.save()
A Document object is actually a QuerySet object. It lazily queries the database when you need the data. QuerySet objects perform searches on the data base using functions like…
first() to retrieve the first object that matches with the provided query.count() to know the number of objects that matche with the provided query.for post in Post.objects: print post.title
for post in TextPost.objects: print post.content
for post in Post.objects(tags='mongodb'): print post.title