MongoEngine 是一个用于 Python 的 ODM(对象文档映射)库,可以让你方便地与 MongoDB 数据库进行交互。它提供了面向对象的方式来定义模型,并对 MongoDB 的数据进行 CRUD(创建、读取、更新、删除)操作。
pip install mongoengine
from mongoengine import connect
connect('mydatabase')
文档模型是与 MongoDB 集合对应的类。在 MongoEngine 中,定义一个文档模型通常是通过继承 Document
类来实现的。
from mongoengine import Document, StringField, IntField, DateTimeField
import datetime
class User(Document):
name = StringField(required=True, max_length=200)
email = StringField(required=True, unique=True)
age = IntField(required=True)
created_at = DateTimeField(default=datetime.datetime.utcnow)
user = User(name="John Doe", email="john@example.com", age=30)
user.save() # 保存到数据库
# 查找所有用户
users = User.objects()
# 根据条件查找
user = User.objects(name="John Doe").first()
# 根据主键(ID)查找
user = User.objects.with_id("60c72b2f5f4b5c6d7c8e1d0a")
user = User.objects(name="John Doe").first()
if user:
user.update(set__age=31)
user = User.objects(name="John Doe").first()
if user:
user.delete()
MongoEngine 允许你将一个文档嵌入到另一个文档中
from mongoengine import EmbeddedDocument, EmbeddedDocumentField, ListField
class Address(EmbeddedDocument):
street = StringField(max_length=200)
city = StringField(max_length=100)
class User(Document):
name = StringField(required=True, max_length=200)
addresses = ListField(EmbeddedDocumentField(Address))
# 创建用户并添加地址
address = Address(street="123 Main St", city="New York")
user = User(name="Jane Doe", addresses=[address])
user.save()
可以在字段上设置索引和唯一性约束
class User(Document):
name = StringField(required=True, max_length=200)
email = StringField(required=True, unique=True)
age = IntField(required=True)
meta = {
'indexes': [
'email', # 为 email 字段创建索引
{'fields': ['name', 'age'], 'unique': True} # 联合唯一索引
]
}