【问题标题】:Overwrite json file in mongodb with python用python覆盖mongodb中的json文件
【发布时间】:2020-09-12 14:37:49
【问题描述】:

我当前的代码不会覆盖存储在 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")

【问题讨论】:

  • 你可以使用collection.replace_one
  • @deadshot “过滤器”标签应该是什么? collection.replace_one(filter?, file_data)
  • @deadshot 我应该像这样使用集合顶部的 _id:collection.replace_one('_id': 'ObjectId("5f5...."'
  • 是的,你可以使用_id 字段
  • @deadshot 此代码不起作用:Collection.replace_one({'_id': "ObjectId('5f5cdc551a462a76a876a490')"}, file_data) replace_one 括号内是否带有 ' 或 "?

标签: python json mongodb


【解决方案1】:

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

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

希望对你有所帮助。

【讨论】:

  • 我不需要更新,我需要做的就是替换。这种方法仅用于替换吗?
  • 如何最好地替换文档?并且不要发布链接仅回答添加一个示例如何解决 OP 的问题
  • 它也适用于替换。如果您只想替换文档,还有其他选项。 replace_one(),replace_many()。
猜你喜欢
  • 1970-01-01
  • 2014-02-06
  • 2015-01-20
  • 1970-01-01
  • 2019-01-02
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多