mongo ORM 笔记
工作中, 使用ORM操作mongo数据库. 总体感觉是, 与django ORM操作类似, 也能方便地使用pymongo的接口.
1. 使用方法
环境:
- python 3.x
- mongoengine
model定义
import datetime
from mongoengine import *
class CommentModel(DynamicDocument):
meta = {
'indexes': [
{
'fields': ['name'],
"cls": True,
"unique": True,
}
]
}
name = StringField(required=True, max_length=32)
age = IntField()
create_at = DateTimeField(default=datetime.datetime.now)
基本操作:
- save(insert/update):
CommentModel.objects().save(instance)
- search:
CommentModel.objects(name="ABC").first()
orCommentModel.objects(__raw__={"name":"ABC"}).first()
2. group用法
2.1 简单统计
统计消费者的消费订单号:
res_list = OrderModel.objects().aggregate(
{'$match': {
OrderModel.buyer_id.name: {"$in": list(set(buyer_id_list))}
}},
{"$group": {
"_id": "${}".format(OrderModel.buyer_id.name),
"order_id": {"$addToSet": "${}".format(OrderModel.order_id.name)}
}}
)
buyer_vs_order_dict = {res["_id"]: res["order_id"] for res in res_list}