簡體   English   中英

PyMongo如果值不是NaN,則僅在文檔中包含字段

[英]PyMongo Only include field in document if value is not a NaN

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

我的插入開始看起來像這樣

            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)

使用math.isnan()來檢查我的值之一是否為NaN很容易,但是在這種情況下,我不知道如何將整個字段留空。

使用math.isnan()來檢查我的值之一是否為NaN很容易,但是在這種情況下,我不知道如何將整個字段留空。

根據您的示例代碼,您可以改為執行以下操作:

# 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 / except中,以檢測數據庫插入錯誤,該錯誤處理應該與文檔創建錯誤不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM