import mongoengine
# 连接到 MongoDB 数据库
mongoengine.connect(
'b017bdb', host='mongodb://admin:password@localhost:27017/')
class User(mongoengine.Document):
name = mongoengine.StringField(required=True)
age = mongoengine.IntField()
email = mongoengine.StringField()
def __repr__(self):
return f"<User(name={self.name}, age={self.age}, email={self.email})>"
# 创建新的用户对象并保存到 MongoDB
# user = User(name="Alice", age=30, email="alice@example.com")
# user.save()
print('-'*10)
# 查询所有用户
users = User.objects() # 返回所有用户
for user in users:
print(user.to_json())
print('-'*10)
# 查询单个用户
user = User.objects(name="Alice").first()
print(user.to_json())
print('-'*10)
# 查询满足条件的用户
users = User.objects(age__gt=25) # 年龄大于 25 的用户
for user in users:
print(user.to_json())
# 更新单个用户的年龄
# user = User.objects(name="Alice").first()
# if user:
# user.update(age=31) # 将 Alice 的年龄更新为 31
# 更新多个用户
# User.objects(age__lt=30).update(set__age=30) # 将年龄小于 30 的所有用户的年龄更新为 30
# 删除单个用户
# user = User.objects(name="aaa").first()
# if user:
# user.delete()
# # 删除多个用户
# User.objects(age__lt=30).delete() # 删除所有年龄小于 30 的用户
mongoengine.disconnect()