1 # from mongoengine import * 2 from mongoengine import connect, Document, EmbeddedDocument, 3 StringField, IntField, FloatField, ListField, EmbeddedDocumentField 4 5 connect('students') # 连接数据库 6 7 SEX_CHOISE = ( # 设置性别选项 8 ('male', '男'), 9 ('female', '女') 10 ) 11 12 13 class Grade(EmbeddedDocument): 14 """成绩""" 15 name = StringField(required=True) 16 score = FloatField(required=True) 17 18 19 class Student(Document): 20 name = StringField(max_length=32, requiredd=True) 21 age = IntField(required=True) 22 sex = StringField(choices=SEX_CHOISE, required=True) 23 grade = FloatField() 24 address = StringField() 25 grades = ListField(EmbeddedDocumentField(Grade)) 26 # remark = StringField() 27 28 meta = { 29 'collection': 'student', # 设置集合名称 30 'ordering': ['-age'] # 集合按年龄倒序 31 } 32 33 34 class TestMongoEngine(object): 35 36 def add_one(self): 37 """添加一条数据""" 38 yuwen = Grade( 39 name='语文', 40 score=90) 41 shuxue = Grade( 42 name='数学', 43 score=100) 44 stu_obj = Student( 45 name='张三', 46 age=15, 47 sex='male', 48 grades=[yuwen, shuxue] 49 ) 50 # stu_obj.remark = 'remark' 必须在配置数据库时先定义,后续才可以添加 51 stu_obj.save() 52 return stu_obj 53 54 def get_one(self): 55 """查询一条数据""" 56 return Student.objects.first() 57 58 def get_more(self): 59 """查询多条诗句""" 60 # return Student.objects 61 return Student.objects.all() 62 63 def get_one_from_oid(self, oid): 64 """查询指定ID的数据""" 65 return Student.objects.filter(id=oid).first() # 注意:根据id查询数据时一定要添加first(),不然报错或查不到数据 66 67 def update(self): 68 """修改数据""" 69 # 修改一条数据 70 # rest = Student.objects.filter(sex='male').update_one(inc__age=1) 71 # return rest 72 # 修改多条数据 73 rest = Student.objects.filter(sex='male').update(inc__age=1) 74 # 年龄增加1岁,文档:https://mongoengine-odm.readthedocs.io/guide/querying.html#advanced-queries 75 # 查询条件(filter)里面可以增加gt__age=16表示年龄大于16岁,文档:https://mongoengine-odm.readthedocs.io/guide/querying.html#query-operators 76 return rest 77 78 def delete(self): 79 """删除数据""" 80 # 删除一条数据 81 return Student.objects.filter(sex='male').first().delete() 82 # 删除多条数据 83 return Student.objects.filter(sex='male').delete() 84 85 86 def main(): 87 obj = TestMongoEngine() 88 # rest = obj.add_one() 89 # print(rest.id) 90 91 # rest = obj.get_one() 92 # print(rest.id, rest.name, rest.grades) 93 94 # rest = obj.get_more() 95 # for row in rest: 96 # print(row.name) 97 98 rest = obj.get_one_from_oid("5e83f7e16490e7f8a4e4e284") 99 if rest: 100 print(rest.name) 101 else: 102 print("查询的数据不存在") 103 104 # rest = obj.update() 105 # for row in rest: 106 # print(row.age) 107 108 # rest = obj.delete() 109 # print(rest) # 删除一条时返回None,删除多条是返回删除的数据条数 110 111 112 if __name__ == '__main__': 113 main()