使用Pymongo Upsert在MongoDB中使用Python更新或创建文档 [英] Using Pymongo Upsert to Update or Create a Document in MongoDB using Python

查看:31
本文介绍了使用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更新或创建文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆