【问题标题】:Is there a way to upsert dataframe in mongoDB?有没有办法在 mongoDB 中插入数据框?
【发布时间】:2020-12-04 20:52:34
【问题描述】:

我在 MongoDB 中有一个现有数据,其中主键设置为“日期”,其中包含一些字段。

我想将具有相同字段的新熊猫数据框插入到 MongoDB 中的现有数据框

例如,我有一个看起来像的 df

我想插入看起来像这样的df

所以复制的索引 2017-05-19 21:19:00, 2017-05-19 21:20:00, 2017-05-19 21:21:00 使用新值进行更新,并将其他新索引添加到现有 df

所以最终的df应该是这样的

我正在使用

    try:
        cursor.insert_many(data, ordered=False)
    except pymongo.errors.BulkWriteError as e:
        print(e.details['writeErrors'])

要做到这一点,这个函数在追加新索引时效果很好,但是会抛出

'keyValue': {'date': datetime.datetime(2020, 8, 15, 9, 24)}, 'errmsg': 'E11000 duplicate key error collection: bitcoin.raw index: date_1 dup key: { date: new Date(1597483440000) }'

重复索引的错误类型。

有没有办法解决这个问题? 提前致谢。

【问题讨论】:

    标签: pandas mongodb dataframe pymongo upsert


    【解决方案1】:

    您不能使用insert_many()。您将需要迭代数据框并为每条记录使用replace_one(),并使用与日期和upsert=True 设置匹配的过滤器。

    使用类似的东西:

    for row in df.to_dict(orient='records'):
        db.mycollection.replace_one({'date': row.get('date')}, row, upsert=True)
    

    【讨论】:

    • 哇,非常感谢。你拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2016-05-06
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多