簡體   English   中英

如何在導入 JSON 文件時更新 mongo 中的文檔 (pymongo)

[英]How to update documents in mongo on import JSON file (pymongo)

我有一個非常小的測試庫,有5個文件和4個arguments。我想在JSON文件導入過程中導入新文件時更新這些文件(添加新字段,用新值替換舊值)。

在此處輸入圖像描述

以前,我在導入一個CSV文件的過程中能夠做到這一點。

CSV文件代碼:

    def update_and_add_with_csv(self, data, key):

        """ The function update all documents in collection databases using csv file
        (add new columns and change old value). Using pandas """

        df = pd.read_csv(data, low_memory=False)
        df = df.to_dict('records')

        key = key

        try:
            startTime = time.time()

            for row in df:
                self.collection.update_one({key: row.get(key)},  {'$set': row}, upsert=True)
            endTime = time.time()
            totalTime = endTime - startTime
            totalTime = str('{:>.3f}'.format(totalTime))

如何使用 JSON 完成此操作?

JSON 文件如下:

在此處輸入圖像描述

我認為最好的方法是不更新這些文檔,而是替換它們。

我假設您的日期字段可以用作唯一標識符。

def update_and_add_with_json(self, file_path):

    """ The function update all documents in collection databases using JSON file """

    file_data = json.load(open(file_path, "r"))
    start_time = time.time()
    for record in file_data:
    
        replace = self.collection.find_one_and_replace({"date": record["date"]}, record)
    end_time = time.time()
    total_time = end_time - start_time
    total_time = str('{:>.3f}'.format(total_time))
    return total_time

不確定您的 json 文件是如何格式化的,但如果它的格式化方式與您的架構相同,這應該可以工作,並且可以更輕松地動態添加字段並利用 MongoDB 的無結構功能。

是的,確切地說,它以類似的方式工作。 可能對某人有用

    def update_and_add_with_json(self, data, key):

        """ The function update all documents in collection databases using JSON file """

        with open(data) as file:
            file_data = json.load(file)

        key = key

        try:
            startTime = time.time()

            for row in file_data:
                self.collection.update_one({key: row.get(key)},  {'$set': row}, upsert=True)
            endTime = time.time()
            totalTime = endTime - startTime
            totalTime = str('{:>.3f}'.format(totalTime))

暫無
暫無

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

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