MongoDB Note6: MongoEngine

MongoDB Note6: MongoEngine

0. 官方文档

  • mongoengine是对pymongo的进一步封装

1. 安装

pip install mongoengine

2. 连接

2.1 连接方式一(推荐)

from mongoengine import * from datetime import datetime connect('demo', alias='db1', host="192.168.92.145", port=27017, username='demodb', password='password',) class Categories(Document): ' 继承Document类,为普通文档 ' name = StringField(max_length=30, required=True) artnum = IntField(default=0, required=True) date = DateTimeField(default=datetime.now(), required=True) meta = {"db_alias": "db1", "collection": "permissao"} # 如果required为True则必须赋予初始值,如果有default,赋予初始值则使用默认值 cate = Categories(name="Linux") cate.save() # 保存到数据库
运行,保存数据成功
notion image

2.2 连接方式二:url连接

from mongoengine import * from datetime import datetime connect(host="mongodb://demodb:password@192.168.92.145:27017/demo") # 定义分类文档 class Categories(Document): ' 继承Document类,为普通文档 ' name = StringField(max_length=30, required=True) artnum = IntField(default=0, required=True) date = DateTimeField(default=datetime.now(), required=True) # 如果required为True则必须赋予初始值,如果有default,赋予初始值则使用默认值 cate = Categories(name="Linux") cate.save() # 保存到数据库
运行。保存数据成功。
notion image