pymongo来操作MongoDB数据库,但是直接把对于数据库的操作代码都写在脚本中,这会让应用的代码耦合性太强,而且不利于代码的优化管理
一般应用都是使用MVC框架来设计的,为了更好地维持MVC结构,需要把数据库操作部分作为model抽离出来,这就需要借助MongoEngine
MongoEngine是一个对象文档映射器(ODM),相当于一个基于SQL的对象关系映射器(ORM)
MongoEngine提供的抽象是基于类的,创建的所有模型都是类
安装
pip install mongoengine
使用时先声明一个继承自MongoEngine.Document的类
在类中声明一些属性,相当于创建一个用来保存数据的数据结构,即数据已类似数据结构的形式存入数据库中,通常把这样的一些类都存放在一个脚本中,作为应用的Model模块
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 = Users.objects.all() #返回所有的文档对象列表
for u in users:
print("name:",u.name,",age:",u.age)
保存文档
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)
user1 = Users(
name='zz',
age= 11
)
user1.save()
print(user1.name)
user1.name = 'zz11'
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=33).order_by('name')
for u in user_search:
print("name:",u.name,",age:",u.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 = Users.objects(age__gte=10, age__lt=33).order_by('-name')
for u in user_search:
print("name:",u.name,",age:",u.age)
查询name=zz11
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) tmp = Users.objects(name="zz11")
for u in tmp:
print("name:",u.name,",age:",u.age)
修改name=zz11的age加1
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)
tmp = Users.objects(name="zz11").update(inc__age=1)
tmp = Users.objects(name="zz11")
for u in tmp:
print("name:",u.name,",age:",u.age)
修改name=zz11的age设为55
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) tmp = Users.objects(name="zz11").update(set__age=55)
tmp = Users.objects(name="zz11")
for u in tmp:
print("name:",u.name,",age:",u.age)