Python連線MongoDB【mongoengine】
阿新 • • 發佈:2019-02-12
#!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
from mongoengine import connect, Document, StringField, IntField, FloatField, ListField, DateTimeField, \
EmbeddedDocument, EmbeddedDocumentField
connect('students', host='localhost', port=27017)
SEX_CHOICES = (
('male', '男' ),
('female', '女')
)
class Grade(EmbeddedDocument):
""" 成績 """
subject = StringField(required=True)
score = FloatField(required=True)
class Student(Document):
""" 學生 """
meta = {
'collection': 'students', #定義集合名稱
}
name = StringField(max_length=32, required=True ) # max_length最大長度,required=True 不能不填寫
age = IntField(required=True)
grade = FloatField()
address = StringField()
sex = StringField(choices=SEX_CHOICES, required=True) # choices 只能根據定義的SEX_CHOICES選擇
grades = ListField(EmbeddedDocumentField(Grade))
created_at = DateTimeField(default=datetime.now())
class TestMongoEngine(object):
# 新增資料
def add_one(self):
yuwen = Grade(
subject="語文",
score=83
)
english = Grade(
subject="英語",
score=92
)
mathematics = Grade(
subject="數學",
score=95
)
stu_obj = Student(
name="李1",
age=21,
address="ShangHai",
sex='female',
grades=[yuwen, english, mathematics]
)
# stu_obj.remark = "remark"
stu_obj.save()
return stu_obj
# 獲取一條資料
def get_one(self):
return Student.objects.first({})
# 獲取多條資料
def get_More(self):
return Student.objects.all()
# 獲取一條帶條件資料,根據id獲取,id=pk
def get_from_oid(self, oid):
return Student.objects.filter(pk=oid).first()
# 修改資料
def update(self):
"""將所有男生年齡增加2"""
return Student.objects.filter(sex='male').update(inc__age=2)
# 返回結果為修改行數,inc__ 參考文件:http://docs.mongoengine.org/guide/querying.html?highlight=inc__
# 刪除資料
def delete(self):
"""刪除資料"""
return Student.objects.filter(sex='female',name='李1').delete() # 返回結果為刪除行數
def main():
obj = TestMongoEngine()
#新增資料
# rest = obj.add_one()
# print(rest.name)
# 獲取一條資料
# rest = obj.get_one()
# print(rest.grades[0].score)
# 獲取多條資料
# rest = obj.get_More()
# print(type(rest), rest[0].name)
# 獲取一條帶條件資料
# rest = obj.get_from_oid('5b10f316485e2e4a9416090e')
# print(rest.name)
# 修改資料
# rest = obj.update()
# print(rest)
# 刪除資料
# rest = obj.delete()
# print(rest)
if __name__ == '__main__':
main()
當新增文件如:
# stu_obj.remark = "remark"
在class Student中沒有定義,新增時則remark無法新增,
這時可以修改class Student的定義:
class Student(DynamicDocument):
......
......