```import pandas as pd
def generate_update_statement(row):
"""
Generate an update statement for MongoDB based on row data.
Args:
row (pandas.Series): A pandas Series representing a row of data.
Returns:
str: The update statement for MongoDB.
"""
# Extracting values from the row, with default values if not present
replace_id = str(row["_id"])
new_total = row.get('new_total', '1')
sales_volume = row.get('销量', '1')
mall_code = row.get('mallCode', '00004539')
# Constructing the replacement column string
replace_col = f"total:NumberInt('{new_total}'), count:NumberInt('{sales_volume}'), mallcode:'{mall_code}'"
# Constructing the update statement
update_statement = ("db.salesDetail.update("
+f"{{'_id': ObjectId('{replace_id}')}},"
+f" {{$set: {{{replace_col}}}}}"
+")"
)
return update_statement
# 创建示例 DataFrame
data = {
"_id": [1, 2, 3],
"new_total": [100, 200, 300],
"销量": [50, 70, 90],
"mallCode": ["A", "B", "C"]
}
df = pd.DataFrame(data)
display(df)
# 测试函数
df['更新语句'] = df.apply(generate_update_statement, axis=1)
# 打印生成的更新语句
#for statement in update_statements:
# print(statement)
# 设置显示的最大列宽度为None,这样就能够完全展示所有内容
pd.set_option('display.max_colwidth', None)
display(df)
输出结果是: