mongoengine 的简单使用

from mongoengine import *

# 进行数据库的连接验证
def connect_mongodb():
"""
host: The IP of the Mongo database.
db: The database name.
username: The user name.
password: Mongodb database password.
authentication_source: User validation from the ADMIN library.

:return:
"""
connect('db', host='mongodb://127.0.0.1/', username='root', password='password',
authentication_source="admin")

# 注册表
class Information(Document):
message_id = StringField(required=True, max_length=200)
title = StringField(required=True, max_length=200, default='hello word') # default 添加默认值
content = StringField(required=True, max_length=200)
addition = StringField(required=True, max_length=200)
created = IntField(required=True, default=time.time())
meta = {
# 'allow_inheritance': True, # 允许继承
"collection": "notify.informs", # 配置集合名, 若不配置默认为类名
"indexes": [{'fields': ['-message_id'], 'unique': True, 'sparse': True, 'types': False}] # 创建索引 倒序 唯一
}
 
class Information(object):

def __init__(self):

self._info = _DBInformation

def find(self, **kwargs):
conditions = {}
if "to_users" in kwargs:
conditions["to_users"] = kwargs.get("to_users")
if "message_id" in kwargs:
conditions["message_id"] = kwargs.get("message_id")
# 按照创建时间的正序排序 order_by("created")
# 按照创建时间的倒序排序 order_by("-created")
data = json.loads(self._info.objects(**conditions).order_by("-created").to_json())
# raw使用操作符
# data = json.loads(self._info.objects(raw=conditions).order_by("-created").to_json())
# data = json.loads(self._info.objects(**conditions).to_json())
[i.pop("_id") for i in data if "_id" in i]
return data

def creat(self, **kwargs):
data = self._info(**kwargs)
data.save()

def update_one(self, message_id, **kwargs):
# data = self._info(message_id=message_id)
# self._info.objects._collection 使用原生 sql语句
self._info.objects._collection.find_one_and_update(
{"message_id": message_id}, {"$set": {"to_users": "11111111"}}, return_document=True)
return

def delete(self, message_id):
self._info.objects(message_id=message_id).delete()
 
 
原文地址:https://www.cnblogs.com/yanhui1995/p/13293633.html