【发布时间】: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")
【问题讨论】:
-
@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 括号内是否带有 ' 或 "?