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

10 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
Run Code Online (Sandbox Code Playgroud)

我有以下代码,用于检查 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)
Run Code Online (Sandbox Code Playgroud)

但是,如果它确实存在,我希望它用新值更新该行。有谁知道如何做到这一点?我看过 pymongo upsert 但我不知道如何使用它。有人可以帮忙吗?

'''''''更新'''''''

上面的内容现在部分有效,但是,我现在收到以下代码的错误:

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)
Run Code Online (Sandbox Code Playgroud)

错误:

InvalidDocument: documents must have only string keys, key was 1
Run Code Online (Sandbox Code Playgroud)

mel*_*r55 18

可能很多人会对接受的答案感到困惑,因为它建议与标志replace_one一起使用upsert

Upserting 的意思是“更新或插入”(Up = 更新,sert= 插入)。对于大多数想要“更新插入”的人来说,他们应该update_oneupsert标志一起使用。

例如:

collection.update_one({'matchable_field': field_data_to_match}, {"$set": upsertable_data}, upsert=True)
Run Code Online (Sandbox Code Playgroud)


Bel*_*ter 9

要更新插入,您不能使用insert()(已弃用)insert_one()insert_many(). 您必须使用支持更新插入的集合级别运算符之一。

首先,我将引导您逐行读取数据帧并replace_one()在每一行上使用。有更高级的方法可以做到这一点,但这是最简单的。

你的代码看起来有点像:

collection.replace_one({'Student': student, 'Date': date}, record, upsert=True)
Run Code Online (Sandbox Code Playgroud)