mongoengine的使用
作者:互联网
本文摘自 https://blog.csdn.net/xc_zhou/article/details/80837962
如有侵权,请联系删除
pymongo的弊端
pymongo来操作mongodb数据库,但是直接把数据库的操作代码写在脚本中,使得应用代码的耦合性太强,不利于代码的优化管理
mongoengine是一个对象文档映射器(ODM),相当于基于sql对象关系映射器(ORM)
安装mongoengine
pip install mongoengine
事先声明一个继承mongoengine.document的类
from mongoengine import * connect('test', host='localhost', port=27017) class Users(Document): name = StringField(required=True, max_length=200) age = IntField(required=True) users = Users.objects.all() #返回所有的文档对象列表 for u in users: print("name:",u.name,",age:",u.age)
保存文档
from mongoengine import * connect('test', host='localhost', port=27017) class Users(Document): name = StringField(required=True, max_length=200) age = IntField(required=True) user1 = Users( name='zz', age= 11 ) user1.save() print(user1.name) user1.name = 'zz123' user1.save() print(user1.name)
查询年龄大于等于10,小于30的,按姓名排列
from mongoengine import * connect('test', host='localhost', port=27017) import datetime class Users(Document): name = StringField(required=True, max_length=200) age = IntField(required=True) User_search = Users.objects(age__gte=10,age__lt=30).order_by('name') #倒序('-name')
for search in User_search:
print(search.name)
查询name为詹姆斯的人
user_search = Users.objects(name='詹姆斯') for search in user_search: print(search.name)
修改name为詹姆斯的age加1
user_update = Users.objects(name='詹姆斯').update(inc__age=1) #修改完成之后要在查询一遍 user_search = Users.objects(name='詹姆斯') for user in user_search: print(user.name)
修改name为詹姆斯的age为18
user_update=Users.objects(name='詹姆斯').update(set__age=18) user_search = Users.objects(name='詹姆斯') 。。。
python中使用mongoengine
from mongoengine import * from datetime import datetime #连接数据库:test # connect('test') # 连接本地test数据库 connect('test', host='127.0.0.1', port=27017, username='test', password='test') # Defining our documents # 定义文档user,post,对应集合user,post class User(Document): # required为True则必须赋予初始值 email = StringField(required=True) first_name = StringField(max_length=50) last_name = StringField(max_length=50) date = DateTimeField(default=datetime.now(), required=True) # 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) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment)) # 允许继承 meta = {'allow_inheritance': True} class TextPost(Post): content = StringField() class ImagePost(Post): image_path = StringField() class LinkPost(Post): link_url = StringField() class Page(DynamicDocument): title = StringField(max_length=200, required=True) date_modified = DateTimeField(default=datetime.now())
添加数据
john = User(email='john@example.com', first_name='John', last_name='Tao').save() ross = User(email='ross@example.com') ross.first_name = 'Ross' ross.last_name = 'Lawley' ross.save() comment1 = Comment(content='Good work!',name = 'LindenTao') comment2 = Comment(content='Nice article!') post0 = Post(title = 'post0',tags = ['post_0_tag']) post0.comments = [comment1,comment2] post0.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() # Create a new page and add tags page = Page(title='Using MongoEngine') page.tags = ['mongodb', 'mongoengine'] page.save()
查看数据
# 查看数据 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:', post.link_url # 通过引用字段直接获取引用文档对象 for post in TextPost.objects: print post.content print post.author.email au = TextPost.objects.all().first().author print au.email # 通过标签查询 for post in Post.objects(tags='mongodb'): print post.title num_posts = Post.objects(tags='mongodb').count() print 'Found %d posts with tag "mongodb"' % num_posts # 多条件查询(导入Q类) User.objects((Q(country='uk') & Q(age__gte=18)) | Q(age__gte=20)) # 更新文档 ross = User.objects(first_name = 'Ross') ross.update(date = datetime.now()) User.objects(first_name='John').update(set__email='123456@qq.com') //对 lorem 添加商品图片信息 lorempic = GoodsPic(name='l2.jpg', path='/static/images/l2.jpg') lorem = Goods.objects(id='575d38e336dc6a55d048f35f') lorem.update_one(push__pic=lorempic) # 删除文档 ross.delete()
标签:name,StringField,mongoengine,objects,使用,print,post 来源: https://www.cnblogs.com/zty1304368100/p/11365763.html