使用Pymongo Upsert在MongoDB中使用Python更新或创建文档

2022-03-14 00:00:00 python mongodb pymongo

问题描述

我有一个数据帧,其中包含我想要上传到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)

相关文章