首页 > 解决方案 > 用python覆盖mongodb中的json文件

问题描述

我当前的代码不会覆盖存储在 MongoDB 中的 json,而是创建另一个文档。我希望它覆盖。我怎么做?

以下是我当前的代码

import json
import pymongo
import dns
from pymongo import MongoClient

# Making Connection
myclient = MongoClient("mongodb+srv://<DBNAME>:<PASSWORD>@<DBNAME>.y3vh0.mongodb.net/<DBNAME>?retryWrites=true&w=majority")

db = myclient["PlayerPrices"]

Collection = db["Playstation"]

# Loading or Opening the json file
with open('players.json') as file:
    file_data = json.load(file)

if isinstance(file_data, list):
    Collection.insert_many(file_data)
else:
    Collection.insert_one(file_data)
    
print("Done")

标签: pythonjsonmongodb

解决方案


关于您的问题,如果您要查找和更新特定文档,最好使用 find_one_and_update() 方法。

https://kb.objectrocket.com/mongo-db/how-to-update-a-mongodb-document-in-python-356

我希望它对你有帮助。


推荐阅读