【问题标题】:Inserting/Updating MongoDB Collection in Python在 Python 中插入/更新 MongoDB 集合
【发布时间】:2020-03-28 01:30:49
【问题描述】:

我在 python 中创建了一个 for 循环,该循环遍历 MongoDB 中的预测集合,并检查是否存在包含相同学生 ID 和今天日期的行。如果有,它应该更新该行,如果没有它应该插入该行。以下是我的代码:

def getPredictions(school):
    schoolDB = DB[school['database']['name']]
    schoolPredictions = schoolDB['session_attendance_predicted']
    Predictions = schoolPredictions.aggregate([{
        '$project': {
            'school': '$school',
            'student':'$student',
            'dateUploaded':'$date',
            'probability':'$probability'
        }        
    }])
    return list(Predictions)

Predictions = getPredictions(school)
Predictions = pd.DataFrame(Predictions)

for i in df.index:
    student = df.loc[i,'students']
    dateToday = date.today()
    probabilityOfLowerThanThreshold = 100       
    dateToday = datetime.datetime.combine(dateToday, datetime.time(0, 0))

    MongoRow = pd.DataFrame.from_dict({'school': {'1': schoolID}, 'student': {'1': student}, 'dateUploaded': {'1': dateToday}, 'probability': {'1': probabilityOfLowerThanThreshold}})
    data_dict = MongoRow.to_dict()

    schoolDB = DB[school['database']['name']]
    collection = schoolDB['session_attendance_predicted']

    for i in Predictions.index:
          collection.replace_one({'student': {'1': student}, 'dateUploaded': {'1': dateToday}}, data_dict, upsert=True)

但是,它不起作用。它根本没有在数据库中产生任何东西,所以 Predictions 集合是空的。如果它不存在,我想插入 data_dict 行。如果它确实存在,那么只需更新它。

有人可以帮忙吗?

【问题讨论】:

  • 我猜你没有打到replace_one 行。那里也没有足够的代码来解决这个问题。我们需要查看您在哪里设置 studentdateTodayPredictions.index
  • @Belly Buster,我已经添加了请求的额外代码。谢谢
  • 你把这当成一顿美餐了。为什么要从 mongo 获取数据,将其放入数据框中,然后再次更新 mongo。数据框给你什么?你能不能试着用真正简单的术语解释你想要做什么。
  • @Belly Buster 我想将 MongoRow 数据框添加到 mongo DB 集合中。但是,如果集合中已经存在具有相同日期和学生的行,则只需使用新的概率和学校对其进行更新

标签: python mongodb pymongo


【解决方案1】:

这个独立的代码示例有望帮助您完成大部分工作。第一次运行它时,它将从数据框中创建一条记录;第二次会更新。

from pymongo import MongoClient
import pandas as pd
import datetime

DB = MongoClient()['mydatabase']

# Seed some test data
data = [['5beee5678d62101c9c4e7dbb', '5bf3e06f9a892068705d8420', '2020-03-27', 0.000038],
        ['5beee5678d62101c9c4e7dbc', '5bf3e06f9a892068705d8421', '2020-03-26', 0.000037]]
df = pd.DataFrame(data, columns=['school', 'student', 'date', 'Probability'])

for rowindex, row in df.iterrows():
    record = row.to_dict()
    record['date'] = datetime.datetime.combine(datetime.date.today(), datetime.time(0, 0))
    DB.session_attendance_predicted.replace_one({'student': row.get('student'), 'date': record['date']}, record, upsert=True)

【讨论】:

  • 有没有办法进行批量 upsert 而不是遍历行以使其更快?
猜你喜欢
  • 1970-01-01
  • 2017-02-25
  • 2020-07-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多