【问题标题】:Bulk insert, update values mongodb批量插入,更新值 mongodb
【发布时间】:2019-09-27 17:22:14
【问题描述】:

我每天都运行批量插入 cron 作业。但是有些值会丢失,当我重新运行数据时,这些值会添加到现有数据中,而不是更新。有没有办法只插入尚未插入的文档。

我的代码:

query = bigQuery.get_data(query)
bulk = col.initialize_unordered_bulk_op()

for i, row in enumerate(query):
    bulk.insert({
        'date': str(row['day_dt']),
        'dt': datetime.strptime(str(row['day_dt']), '%Y-%m-%d'),
        'site': row['site_nm'],
        'val_counts': row[8]
    })

bulk_result = bulk.execute()

现在,它会在每次查询运行时重新插入所有值。有没有办法只添加尚未添加的值。

【问题讨论】:

  • 你应该先检查记录是否存在,如果不存在,插入它。
  • @securisec,我对此很陌生。我该怎么做?
  • 您可以使用findOne。所以col.find_one(query) 其中query 是您对数据的了解,和/或ObjectID

标签: python mongodb bulkinsert bulkupdate bulk-operations


【解决方案1】:

我显然不完全了解您的数据结构,也不完全清楚您要做什么,但我认为应该这样做。

query = bigQuery.get_data(query)

new_things = []
for i, row in enumerate(query):
    if not col.find_one(your_query): # make sure that the document does not exist already
        # add data to an array
        new_things.append({
        'date': str(row['day_dt']),
        'dt': datetime.strptime(str(row['day_dt']), '%Y-%m-%d'),
        'site': row['site_nm'],
        'val_counts': row[8]
    })

# use insert_many to insert all the documents
bulk_result = col.insert_many(newthings)

查看代码旁边的 cmets 以获得解释。如果您像您提到的那样是菜鸟,我会坚持使用更简单的做事方式,并随着您经验的增长扩展您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多