2016-10-03 63 views
0

我有大量需要使用PyMongo插入到MongoDB數據庫中的數據。我擁有的數據目前存儲在平面文件中並且很稀疏(即許多單個值爲NaN)。在Mongo DB中,如果值是NaN,我不想插入字段,但我不知道該怎麼做(我應該指出我對MongoDB和Python都是新手)。PyMongo如果值不是NaN,則只包含文檔中的字段

我插入startement看起來像這樣

  strategy.insert_many([ 
      { 
       "strategyId": strategyInfo[stratIndex][ID], 
       "strategyName": strategyInfo[stratIndex][NAME], 
       "date": dates[i], 
       "time": thisTime, 
       "aum": stratAum[i], 
       "return":0.0, 
       "commission":0.0, 
       "slippage":0.0, 
       "basket":[{ 
        "assetId": assets[m][ASSETID], 
        "order": orders[i, m], 
        "expiry": expiry[i, m], 
        "price": prices[i, m], 
        "ePrice": eprices[i, m]  <<<Don't include line if eprices[i,m] is a NaN 
       } 
        for m in range(len(assets)) 
       ] 
      } 
     ], False) 

這是很容易檢查,看看我的價值的一個是NaN使用math.isnan()但我無法弄清楚如何讓整場空白,如果這是這樣的。

+0

如何修復您的數據。什麼是數據的來源? – styvane

+0

數據在內部生成。沒有什麼問題。缺失的值是故意的。 –

回答

0

這是很容易檢查,看看我的價值的一個是NaN使用math.isnan()但我無法弄清楚如何讓整場空白,如果是這樣的話。

根據您的示例代碼,你可以做,而不是執行以下操作:

# Create a strategy document. 
# This is inside of a loop where variable `i` is known, similar to your example. 
doc = { 
    "strategyId": strategyInfo[stratIndex][ID], 
    "strategyName": strategyInfo[stratIndex][NAME], 
    "date": dates[i], 
    "time": thisTime, 
    "aum": stratAum[i], 
    "return":0.0, 
    "commission":0.0, 
    "slippage":0.0 
} 
baskets = [] 
for m in range(len(assets)): 
    basket = { 
     "assetId": assets[m][ASSETID], 
     "order": orders[i, m], 
     "expiry": expiry[i, m], 
     "price": prices[i, m], 
    } 
    if not math.isnan(eprice[i, m]): 
     basket["ePrice"] = eprice[i, m] 
    baskets.append(basket) 

# You can also add a filter here to make sure `baskets` array is not null. 
doc["basket"] = baskets 
docs.append(doc) 

基本上分離使您的文件和數據庫插入。

然後可以使用insert_many()

strategy.insert_many(docs, False) 

您也可以包裝insert_many在try /除了檢測數據庫插入錯誤,這應該是不同的錯誤從您的文檔創建錯誤處理。

相關問題