zoukankan      html  css  js  c++  java
  • 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()
     
     
  • 相关阅读:
    centos 6.5安装erlang和RabbitMQ
    vert.x学习(八),用JDBCClient配合c3p0操作数据库
    vert.x学习(七),使用表单获取用户提交的数据
    vert.x学习(六),动态模板与静态文件的结合
    vert.x学习(五),用StaticHandler来处理静态文件
    函数-生成器、迭代器
    函数装饰器
    函数参数、作用域、高阶函数、递归函数、高阶函数
    深浅拷贝、集合set、函数、日志
    第一部分day5 文件操作
  • 原文地址:https://www.cnblogs.com/yanhui1995/p/13293633.html
Copyright © 2011-2022 走看看