试图将新数据插入mongo数据库,该数据库可能故意包含重复项

2024-09-28 22:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码使用Pandas内置的数据收集算法收集了一堆etf的数据,每天和每天结束时都有大约5年的数据。我的索引是datetime索引。你知道吗

当我创建历史数据库时,一切都很顺利。现在,我想用cron作业每天更新我的数据库,为此,我创建了一个时间“缓冲区”。你知道吗

所以我的想法是,当我尝试插入数据库中已经存在的数据时,mongo会跳过它(毕竟,我创建了date作为索引)。因此,有了这个想法,如果一个或几个股票在过去几天没有数据,通过尝试插入冗余数据,我可以有一个完整的数据库。你知道吗

但是,我得到以下错误:

DuplicateKeyError: E11000 duplicate key error collection: ETFs.EEM index: id dup key: { : new Date(1524700800000) }

我的理解是mongo应该跳过这个。这个代码怎么了?你知道吗

def insert_to_mongo():
    for x in etfs.keys():
        print 'Processing ' + x
        data_points = len(etfs[x])
        for i in range(data_points):
            data = ({
                '_id': etfs[x].index[i],
                'open': float(etfs[x].iloc[i]['open']),
                'high': float(etfs[x].iloc[i]['high']),
                'low': float(etfs[x].iloc[i]['low']),
                'close': float(etfs[x].iloc[i]['close']),
                'adj close': float(etfs[x].iloc[i]['adj close']),
                'volume': float(etfs[x].iloc[i]['volume']),
                })
            collection = db[x]
            collection.insert_one(data)
    print 'Inserted data successfully'

Tags: 数据key代码id数据库forclosedata