MongoDB
原生MongoDB SQL
python连接数据库
import pymongo
client = pymongo.MongoClient(host='xxx.xxx.xxx.xxx', port=28018)
db = client['xxxxxx']
db.authenticate('xxxxxx', "xxxxxx")
SQL语句
find
db.hospital_subject_template_test.find({
'填报表格数据.学科建设团队.现有团队': {
'$elemMatch': {
'id': 2,
'学术任职情况.id': 4353445
}
}
})
add
db.catalogue_classify.update(
{'name': f'{big_classify}'},
{'$push': {f'details.{small_classify}': data}}
)
db.catalogue_classify.update(
{'name': f'{big_classify}'},
{'$push': {f'details.{small_classify}': {'$each':[data],'$position':-1}}}
)
db.hospital_subject_template_test.update({
'role': 'h2s1'
}, {
'$addToSet': {
'填报表格数据.学科建设团队.现有团队.$[data1].学术任职情况': {
'test': 'hello——2'
}
}
},{'arrayFilters':[{'data1.id':75}]})
db.hospital_subject_template_test.update({
'role': 'h2s1'
}, {
'$addToSet': {
'填报表格数据.学科建设团队.现有团队': {
'test_1111': 'hello——2'
}
}
})
update
db.catalogue_classify.update(
{'name': big_classify},
{'$set': {f'details.{small_classify}': new_ls}}
)
db.hospital_subject_template_test.update({
'填报表格数据.专利申报.id': 17,
}, {
'$set': {
'填报表格数据.专利申报.$[elem].授权人.0': 'test hello'
}
}, {
'arrayFilters': [{
'elem.id': 17,
}]
})
db.hospital_subject_template_test.findOneAndUpdate({
'填报表格数据.专利申报.id': 1
}, {
'$set': {
'填报表格数据.专利申报.$[data].学科': 'python'
}
},{'arrayFilters':[{'data.id':1}]})
db.hospital_subject_template_test.find_one_and_update(
filter_dict,
{'$set': update_dict},
upsert=True,
array_filters=array_filter,
)
delete
db.hospital_subject_template_test.update(
{f'{table_name}.id': data['id']},
{'$pull': {f'{table_name}': {'id': data['id']}}}
)
db.hospital_subject_template_test.update({
'填报表格数据.学科建设团队.现有团队.id': 2
}, {
'$pull': {
'填报表格数据.学科建设团队.现有团队': {'id':2}
}
})
db.hospital_subject_template_test.update({
'填报表格数据.学科建设团队.现有团队.id': 2
}, {
'$unset': {
'填报表格数据.学科建设团队.现有团队.$.类别': '医生'
}
})
mongoengine
Django 配置数据库
from mongoengine import connect
connect('databaseName', host='xxx.xxx.xxx.xxx', username="username",
authentication_source='databaseName',
password="password", port=28018)
文件上传与下载
文件上传
import mongoengine
class UploadFileDemo(mongoengine.Document):
name = mongoengine.StringField(max_length=255)
filePath = mongoengine.StringField(max_length=255)
fileType = mongoengine.StringField(max_length=255)
meta = {'collection': 'uploadDemo'}
from rest_framework_mongoengine import serializers
class UploadDemoSerializer(serializers.DocumentSerializer):
class Meta:
model = UploadFileDemo
fields = ["name", "filePath"]
from datetime import datetime
from .models import UploadFileDemo
import random
import os
def upload_file_demo(request):
if request.method == 'POST':
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
file = request.FILES.get('filePath')
name = request.POST.get('name')
filename, filetype = str(file.name).split('.')
random_num = random.randint(1000, 9999)
basic_path = f'./uploadFiles/{year}/{month}/{day}/'
if not os.path.exists(basic_path):
os.mkdir(basic_path)
with open(basic_path + f'{filename}#{random_num}.{filetype}', 'wb+') as f:
for chunk in file.chunks():
f.write(chunk)
f.close()
user = UploadFileDemo(name=name, filePath=f'{year}/{month}/{day}/{filename}#{random_num}.{filetype}')
user.save()
return HttpResponse('OK')
文件下载
from .models import UploadFileDemo
from django.http import HttpResponse, JsonResponse
import re
def down_file_demo(request):
name = request.GET.get('name')
try:
data = list(UploadFileDemo.objects.aggregate([{'$match': {'name': name}, }]))
path = data[0]['filePath']
path = re.sub(r'#\d+', "", path)
file = open(f'./uploadFiles/{str(path)}', 'rb')
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream'
filename = f'attachment; filename={path}'
response['Content-Disposition'] = filename.encode('utf-8', 'ISO-8859-1')
return response
except IndexError as e:
data = {
"code": 400,
'message': '查询的id不存在',
'error': e,
}
return JsonResponse(data)