mongoengine使用示例
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2017年10月19日 @author: zzy ''' from mongoengine import * #连接数据库 def lazy_connect(): #mongodb://dbuser:sa123@192.168.1.58:27017/db_datacn connect('db_datacn', host='mongodb://192.168.1.58/', username='dbuser', password='sa123') lazy_connect() # Defining our documents # 定义文档user,post,对应集合user,post class User(Document): email = StringField(required=True) first_name = StringField(max_length=50) last_name = StringField(max_length=50) #Embedded documents 嵌入的文件,it doesn’t have its own collection in the database class Comment(EmbeddedDocument): content = StringField() name = StringField(max_length=120) class Post(Document): title = StringField(max_length=120, required=True) # ReferenceField相当于foreign key author = ReferenceField(User, reverse_delete_rule=CASCADE) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment)) #允许继承 meta = {'allow_inheritance': True} #Post的子类 class TextPost(Post): content = StringField() #Post的子类 class ImagePost(Post): image_path = StringField() #Post的子类 class LinkPost(Post): link_url = StringField() def save_user(): # john = User(email='john@example.com') # john.first_name = 'john' # john.last_name = 'cvsh' # john.save() # # ross = User(email='ross@example.com') # ross.first_name = 'Ross' # ross.last_name = 'Lawley' # ross.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() # for post in Post.objects: # print(post.title) # # for post in TextPost.objects: # print(post.content) # # for post in Post.objects: # print(post.title) # print('=' * len(post.title)) # if isinstance(post, TextPost): # print(post.content) # if isinstance(post, LinkPost): # print('Link: {}'.format(post.link_url)) Post.objects(tags='mongoengine').update(tags=['abc','20171019']) for post in Post.objects.all(): #for post in Post.objects(tags='mongoengine'): print(post.title) #Post.objects(tags='mongodb').delete() num_posts = Post.objects(tags='mongodb').count() print('Found {} posts with tag "mongodb"'.format(num_posts)) if __name__ == '__main__': save_user()