Using Pymongo Upsert to Update or Create a Document in MongoDB using Python(使用Pymongo Upsert在MongoDB中使用Python更新或创建文档)
本文介绍了使用Pymongo Upsert在MongoDB中使用Python更新或创建文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据帧,其中包含我想要上传到MongoDB的数据。以下是数据:
MongoRow = pd.DataFrame.from_dict({'school': {1: schoolID}, 'student': {1: student}, 'date': {1: dateToday}, 'Probability': {1: probabilityOfLowerThanThreshold}})
school student date Probability
1 5beee5678d62101c9c4e7dbb 5bf3e06f9a892068705d8420 2020-03-27 0.000038
我有以下代码,用于检查mongo中的行是否包含相同的学生ID和日期,如果不包含,则添加该行:
def getPredictions(school):
schoolDB = DB[school['database']['name']]
schoolPredictions = schoolDB['session_attendance_predicted']
Predictions = schoolPredictions.aggregate([{
'$project': {
'school': '$school',
'student':'$student',
'date':'$date'
}
}])
return list(Predictions)
Predictions = getPredictions(school)
Predictions = pd.DataFrame(Predictions)
schoolDB = DB[school['database']['name']]
collection = schoolDB['session_attendance_predicted']
import json
for i in Predictions.index:
schoolOld = Predictions.loc[i,'school']
studentOld = Predictions.loc[i,'student']
dateOld = Predictions.loc[i,'date']
if(studentOld == student and date == dateOld):
print("Student Exists")
#UPDATE THE ROW WITH NEW VALUES
else:
print("Student Doesn't Exist")
records = json.loads(df.T.to_json()).values()
collection.insert(records)
但是,如果它确实存在,我希望它用新值更新该行。有人知道怎么做吗?我看过pymongo upsert,但不知道怎么用。有人能帮忙吗?
‘UPDATE’
以上现在部分正常工作,但是,我现在收到以下代码的错误:
dateToday = datetime.datetime.combine(dateToday, datetime.time(0, 0))
MongoRow = pd.DataFrame.from_dict({'school': {1: schoolID}, 'student': {1: student}, 'date': {1: dateToday}, 'Probability': {1: probabilityOfLowerThanThreshold}})
data_dict = MongoRow.to_dict()
for i in Predictions.index:
print(Predictions)
collection.replace_one({'student': student, 'date': dateToday}, data_dict, upsert=True)
错误:
InvalidDocument: documents must have only string keys, key was 1
推荐答案
若要向上插入,不能使用insert()
(已弃用)insert_one()
或insert_many()
。您必须使用支持插入的collection level operators之一。
replace_one()
。有更高级的方法可以做到这一点,但这是最简单的。
您的代码看起来有点像:
collection.replace_one({'Student': student, 'Date': date}, record, upsert=True)
这篇关于使用Pymongo Upsert在MongoDB中使用Python更新或创建文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Pymongo Upsert在MongoDB中使用Python更新或创建文档
基础教程推荐
猜你喜欢
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01