Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python学习笔记:Python操作MongoDB基本用法 #20

Open
AlexZ33 opened this issue Apr 3, 2020 · 0 comments
Open

Python学习笔记:Python操作MongoDB基本用法 #20

AlexZ33 opened this issue Apr 3, 2020 · 0 comments

Comments

@AlexZ33
Copy link
Member

AlexZ33 commented Apr 3, 2020

MongoDB 服务
使用 Docker 运行 MongoDB 服务:

docker run
-e MONGO_INITDB_ROOT_USERNAME=admin
-e MONGO_INITDB_ROOT_PASSWORD=123456
-p 27017:27017
-d mongo:4
配置了 root 用户和密码,以及与宿主机的端口映射关系

通过 MongoEngine 操作数据库
MongoEngine 是基于 PyMongo 开发的 ORM 库,详见:MongoEngine

建立连接
import mongoengine

def init_mongo():
mongoengine.connection.connect('lbs',
host='127.0.0.1',
port=27017,
username='admin',
password='123456',
authentication_source='admin')

init_mongo()
连接只需要建立一次

数据对象模型
为项目数据配置一个模型类:

from mongoengine import *

class Group(Document):
group_id = LongField(required=True, unique=True)
group_item = ListField(required=True)
查询
查询单条数据:

Group.objects.get(group_id=1)
查询多条数据:

Group.objects(group_item=[1, 2])
字段过滤:

Group.objects(group_id=1).exclude('id')
修改
group = Group.objects.get(group_id=1)
group.group_item = [2, 3]
group.save()
格式转换
JSON 序列化:

Group.objects(group_id=1)[0].to_json()
反序列化:

import json

group_json = Group.objects(group_id=1)[0].to_json()
group_dict = json.loads(group_json)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant