文章参考:https://blog.csdn.net/xc_zhou/article/details/80837962
mongoengine
简介
pymongo来操作MongoDB数据库,但是直接把对于数据库的操作代码都写在脚本中,这会让应用的代码耦合性太强,而且不利于代码的优化管理
一般应用都是使用MVC框架来设计的,为了更好地维持MVC结构,需要把数据库操作部分作为model抽离出来,这就需要借助MongoEngine
MongoEngine是一个对象文档映射器(ODM),相当于一个基于SQL的对象关系映射器(ORM)
MongoEngine提供的抽象是基于类的,创建的所有模型都是类
1基本使用
#pip install mongoengine # 安装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)
users = () #返回所有的文档对象列表for u in users:
print("name:",,",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
)
()
print() # zz
= 'zz11'
() # 保存后,age还是11print() # zz11
查询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 = (age__gte=10, age__lt=33).order_by('name')
for u in user_search:
print("name:",,",age:",)
查询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 = (age__gte=10, age__lt=33).order_by('-name')
for u in user_search:
print("name:",,",age:",)
查询name=zz11
from mongoengine import *
connect('test', host='localhost', port=27017)
import datetime
class Users(Document):
nam