Python中使用MongoEngine

pymongo來操做MongoDB數據庫,可是直接把對於數據庫的操做代碼都寫在腳本中,這會讓應用的代碼耦合性太強,並且不利於代碼的優化管理數據庫

通常應用都是使用MVC框架來設計的,爲了更好地維持MVC結構,須要把數據庫操做部分做爲model抽離出來,這就須要藉助MongoEngine數據結構

MongoEngine是一個對象文檔映射器(ODM),至關於一個基於SQL的對象關係映射器(ORM)框架

MongoEngine提供的抽象是基於類的,建立的全部模型都是類優化

 安裝ui

pip install mongoengine

使用時先聲明一個繼承自MongoEngine.Document的類設計

在類中聲明一些屬性,至關於建立一個用來保存數據的數據結構,即數據已相似數據結構的形式存入數據庫中,一般把這樣的一些類都存放在一個腳本中,做爲應用的Model模塊3d

複製代碼

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的,按姓名排列blog

複製代碼

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)

複製代碼

相關文章
相關標籤/搜索