Python之路 【第十四篇】Mongoengine

Mongoengine

官网链接:http://docs.mongoengine.org/guide/index.html

类似于orm进行操作

 

django中使用

1 配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'meanning12',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'CONN_MAX_AGE': 6*60*60,
        'OPTIONS': {
            'autocommit': True,
        },
    },
    'mongodb12': {
        'ENGINE': None,
    }
}

import mongoengine
# 连接mongodb中数据库名称为mongodb12的数据库
#conn = mongoengine.connect("meanning12",username='micagent', password='micagent20180528', authentication_source='admin', host='120.79.186.138', port=27017)
conn = mongoengine.connect("meanning12")
settings.py

 

2 相关操作

序列化:
class GuaSerializer(serializers.Serializer):
    gua_number = serializers.CharField()
    gua_sub_title = serializers.CharField()
    gua_title = serializers.CharField()
    gua_serial_text = serializers.CharField()
    gua_serial = serializers.CharField()
    gua_one = serializers.CharField()
    gua_three = serializers.CharField()
    gua_four = serializers.CharField()
    gua_five = serializers.CharField()
    gua_two = serializers.CharField() #移动到最后
    class Meta:
        model = Gua
        fields = "__all__"

class GuaView(APIView):
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        check_num = request.GET.get('checkNum')
        result = Gua.objects.filter(gua_serial=check_num).first()
        serializer = GuaSerializer(result)
        return Response(data=serializer.data)

模型2:
class Post(Document):
    """
    文章【模型】
    """
    title = StringField()  # 标题
    content_url = StringField()  # 文章链接
    source_url = StringField()  # 原文链接
    digest = StringField()  # 文章摘要
    cover = URLField(validation=None)  # 封面图
    p_date = DateTimeField()  # 推送时间
    author = StringField()  # 作者

    content = StringField()  # 文章内容

    read_num = IntField(default=0)  # 阅读量
    like_num = IntField(default=0)  # 点赞数
    comment_num = IntField(default=0)  # 评论数
    reward_num = IntField(default=0)  # 点赞数

    c_date = DateTimeField(default=datetime.now)  # 数据生成时间
    u_date = DateTimeField(default=datetime.now)  # 数据最后更新时间


模型3
from datetime import datetime

class Todo(db.Document):

    meta = {

        'collection': 'todo',

        'ordering': ['-create_at'],

        'strict': False,

    }

    task = db.StringField()

    create_at = db.DateTimeField(default=datetime.now)

    is_completed = db.BooleanField(default=False)


# 数据查询

todos = Todo.objects().all() # 查询所有数据使用 all() 方法

task = 'cooking'
todo = Todo.objects(task=task).first()  # 查询满足某些条件的数据

todo1 = Todo(task='task 1', is_completed=False)
todo1.save()  # 添加数据使用 save() 方法

# 数据排序
todos = Todo.objects().order_by('create_at')

# 更新数据
task = 'task 1'
todo = Todo.objects(task=task).first()  # 先查找
if not todo:
    return "the task doesn't exist!"
todo.update(is_completed=True)   # 再更新


# 删除数据
task = 'task 6'
todo = Todo.objects(task=task).first()  # 先查找
if not todo:
    return "the task doesn't exist!"
todo.delete()   # 再删除

# 分页
skip_nums = 1
limit = 3
todos = Todo.objects().order_by(
    '-create_at'
).skip(
    skip_nums
).limit(

    limit
)
def view_todos(page=1): # 使用 paginate() 方法
    todos = Todo.objects.paginate(page=page, per_page=10)


from mongoengine import *

# 链接mongodb数据库
# connect('tumblelog')

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

class Comment(EmbeddedDocument): # 嵌入式文档
    content = StringField()
    name = StringField(max_length=120)


class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))
    meta = {'allow_inheritance': True}

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

def create_doc():
    # 创建文档 方式一
    ross = User(email='ross@example.com', first_name='Ross', last_name='Lawley').save()
    # 创建文档 方式二
    john = User(email='johns@example.com')
    john.first_name = 'john'
    john.last_name = 'hua'
    john.save()

def test_save():
    post1 = TextPost(title='Fun with MongoEngine', author=john)
    post1.content = 'Took a look at MongoEngine today, looks pretty cool.'
    post1.tags = ['mongodb', 'mongoengine']
    post1.save()

    post2 = LinkPost(title='MongoEngine Documentation', author=ross)
    post2.link_url = 'http://docs.mongoengine.com/'
    post2.tags = ['mongoengine']
    post2.save()
def look_field():
    for post in Post.objects: # 所继承的post的文档都被打印了
        print(post.title)

    for post in TextPost.objects:
        print(post.title)

# 检索特定于类型的信息
for post in Post.objects:
    print(post.title)
    print('=' * len(post.title))

    if isinstance(post, TextPost):
        print(post.content)

    if isinstance(post, LinkPost):
        print('Link: {}'.format(post.link_url))

# 按标签搜索
for post in Post.objects(tags='mongodb'):
    print(post.title)

# 统计
def count():
    num_posts = Post.objects(tags='mongodb').count()
    print('Found {} posts with tag "mongodb"'.format(num_posts))

#查询
# 1 嵌入文档--下划线查询
# uk_pages = Page.objects(author__country='uk')
# 2 查询运算符 字符串 地理查询 详情链接 http://docs.mongoengine.org/guide/querying.html
# young_users = Users.objects(age__lte=18)
相关操作
# 联合唯一  --------- unique_with
    devEUI = StringField(unique_with='type_id') #  与type_id保证联合唯一
    type_id = ReferenceField(DeviceType)  # 传感器类型id
# 唯一约束  ---------- unique=True
   devEUI = StringField(required=True,unique=True)  # 设备唯一编号

# 更新(添加)字典字段中的某个key值
class UserLinkInfo(mongoengine.Document):
    config = mongoengine.DictField()
更新字典字段key值:UserLinkInfo.objects.filter(channel_name=self.channel_name).update(config__ai_accept=data)


# 聚合分组
# 录入数据
>>> from pymongo import MongoClient
>>> db = MongoClient().aggregation_example
>>> result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]},
...                                 {"x": 2, "tags": ["cat"]},
...                                 {"x": 2, "tags": ["mouse", "cat", "dog"]},
...                                 {"x": 3, "tags": []}])
>>> result.inserted_ids
[ObjectId('...'), ObjectId('...'), ObjectId('...'), ObjectId('...')]
# 聚合框架
管道传递三个操作。1展开tags数组 2标签分组并求和  3 最后按计数排序
>>> from bson.son import SON
>>> pipeline = [
...     {"$unwind": "$tags"},
...     {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
...     {"$sort": SON([("count", -1), ("_id", -1)])}
... ]
>>> import pprint
>>> pprint.pprint(list(db.things.aggregate(pipeline)))
[{u'_id': u'cat', u'count': 3},
 {u'_id': u'dog', u'count': 2},
 {u'_id': u'mouse', u'count': 1}]

示例一:
class Person(Document):
    name = StringField()

Person(name='John').save()
Person(name='Bob').save()

pipeline = [
    {"$sort" : {"name" : -1}},
    {"$project": {"_id": 0, "name": {"$toUpper": "$name"}}}
    ]
data = Person.objects().aggregate(pipeline)


# mongo默认id类型为ObjectId,所以使用id查询时,需将str转换为ObjectId
from bson import ObjectId
user = User.objects.get(id=ObjectId(user_id))
# 优化
user = User.objects.with_id(user_id)

#转换为字典
msg = data.to_mongo().to_dict()
相关操作2

 

posted @ 2021-09-22 18:24  风hua  阅读(60)  评论(0编辑  收藏  举报