我正在尝试扫描文件系统中的文件 - 如果文件在数据库中则更新。如果没有,则插入新记录。但是我收到了这个错误" TypeError update()得到了多个参数值' upsert'"
我在这里做错了什么?
def scan_for_file(dir_path, storage_bucket):
for file in os.listdir(dir_path):
curpath = os.path.join(dir_path, file)
if os.path.isfile(curpath):
print('found file:', file)
print('checking db')
collection = db.file_collection
cursor = collection.find({'file_path': curpath})
for document in cursor:
file_db_id = document['_id']
file_accessed = datetime.datetime.fromtimestamp(os.path.getatime(curpath))
file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
file_created = datetime.datetime.fromtimestamp(os.path.getctime(curpath))
file_size = os.stat(curpath).st_size
file_convert_size = convert_size(file_size)
utc_datetime = datetime.datetime.utcnow()
update_id = collection.update_one({'_id': file_db_id}, {
"$set": {
"file_size": file_convert_size,
"file_size_bytes": file_size,
"process_datestamp": utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
"file_created": file_created,
"file_accessed": file_accessed,
"file_modified": file_modified}},
{
"$setOnInsert": {
"file_path": curpath,
"file_name": file,
"file_size": file_convert_size,
"file_size_bytes": file_size,
"process_datestamp": utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
"file_$reated": file_created,
"file_accessed": file_accessed,
"file_modified": file_modified}}, upsert=True,
)
update_id
print('ID Updated:', file_db_id)
print('updating document id:')
else:
print('This is not a file:', file)
答案 0 :(得分:1)
将更新操作修改为:
update_id = collection.update_one(
{'_id': file_db_id},
{
"$set": {
"file_size": file_convert_size,
"file_size_bytes": file_size,
"process_datestamp": utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
"file_created": file_created,
"file_accessed": file_accessed,
"file_modified": file_modified
},
"$setOnInsert": {
"file_path": curpath,
"file_name": file,
"file_size": file_convert_size,
"file_size_bytes": file_size,
"process_datestamp": utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
"file_$reated": file_created,
"file_accessed": file_accessed,
"file_modified": file_modified
}
},
upsert=True)
您的代码有两个错误:首先,您为{}
和$set
分别添加一个$setOnInsert
docs
另外,你正在做upsert=True,
。看到这个额外的,
,这会导致Python中的元组。