python3之mongoengine

下载

pip install mongoengine

连接数据库

from mongoengine import *
connect("数据库名", host="127.0.0.1", port=27018, username='', password=" ",
        authentication_source="admin", authentication_mechanism="SCRAM-SHA-1")
 # authentication_source="admin", authentication_mechanism="SCRAM-SHA-1" 认证方式

定义表

from datetime import datetime
class Users(Document):
    name = StringField(required=True, max_length=200)
    age = IntField(required=True)
    is_deleted = IntField(default=0, choices=[0, 1])
    create_time = DateTimeField(default=datetime.now())
    update_time = DateTimeField(default=datetime.now())

增删改查

新增

  1. way1—save()
from loguru import logger
def insert_data(data):
	instance = Users(**data)
	res = instance.save()
	logger.debug(res)

data = {"age":"test","age":1}
insert_data(data)
  1. way2–批量插入多个文档
def many_insert():
	instances = []
	names = ["test1","test2"]
	age = 19
	for name in names:
		instances.append(Users(name=name, age=age))
	data = Users.objects.insert(instanes)
	logger.debug(data)
	
many_insert()

  1. way3–create()
def create(data):
	res = Users.objects.create(data)
	logger.debug(res)
data = {"name":"test","age":1}
create(data)

删除

def ture_delete(query):
	"""真删除"""
	queryset = Users.objects.filter(**query)
	delete_count = queryset.delete()
    logger.debug(f"查询数量:{queryset.count()}, 真删除数量:{delete_count}")
query = {"name":"test","age":1}
true_delete(query)

def false_delete(query):
	"""假删除"""
	queryset = Users.objects.filter(**query)
	update_count = queryset.update(is_deleted=1,update_time=datetime.now())
	logger.debug(f"查询数量:{queryset.count()}, 假删除数量:{update_count}")
query = {"name":"test","age":1}
false_delete(query)
	

修改

def update(query, data):
	queryset = Users.objects.filter(query)
	update_count = queryset.update(**data)
	logger.debug(f"查询数量:{queryset.count()}, 更新数量:{update_count}")
query = {"name":"test","age":1}
data = {"name":"test_modify","age":18}
data.update({"update_time":datetime.now()})
update(query)

查询

other

你可能感兴趣的:(数据库,python)