使用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 upstart,但我不知道如何使用它。有人能帮忙吗?

更新

上面的部分工作现在,然而,我现在得到了以下代码的错误:

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

可能很多人会被接受的答案弄糊涂,因为它建议使用replace_oneupsert标志。

Uperting表示"更新或插入"(Up=更新,sert=插入(。对于大多数想要"追加销售"的人来说,他们应该使用带有upsert标志的update_one

例如:

collection.update_one({'matchable_field': field_data_to_match}, {"$set": upsertable_data}, upsert=True)

若要追加启动,您不能使用insert()(已弃用(insert_one()insert_many()。您必须使用一个支持追加销售的集合级别运算符。

为了开始,我将向您介绍逐行读取数据帧,并在每行上使用replace_one()。有更先进的方法可以做到这一点,但这是最简单的。

你的代码看起来有点像:

collection.replace_one({'Student': student, 'Date': date}, record, upsert=True)

最新更新