MongoEngine由Python语言写成,提供一个很类似Django ORM的API 用于访问 MongoDB 数据库。
示例代码:
class BlogPost(Document): title = StringField(required=True, max_length=200) posted = DateTimeField(default=datetime.datetime.now) tags = ListField(StringField(max_length=50)) class TextPost(BlogPost): content = StringField(required=True) class LinkPost(BlogPost): url = StringField(required=True) # Create a text-based post >>> post1 = TextPost(title='Using MongoEngine', content='See the tutorial') >>> post1.tags = ['mongodb', 'mongoengine'] >>> post1.save() # Create a link-based post >>> post2 = LinkPost(title='MongoEngine Docs', url='hmarr.com/mongoengine') >>> post2.tags = ['mongoengine', 'documentation'] >>> post2.save() # Iterate over all posts using the BlogPost superclass >>> for post in BlogPost.objects: ... print '===', post.title, '===' ... if isinstance(post, TextPost): ... print post.content ... elif isinstance(post, LinkPost): ... print 'Link:', post.url ... print ... >>> len(BlogPost.objects) 2 >>> len(TextPost.objects) 1 >>> len(LinkPost.objects) 1 # Find tagged posts >>> len(BlogPost.objects(tags='mongoengine')) 2 >>> len(BlogPost.objects(tags='mongodb')) 1