如何在导入 JSON 文件 (pymongo) 时更新 mongo 中的文档
我的测试基础很小,有5个文档和4个论点。在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文件:
I have a very small test base, with 5 documents and 4 arguments. I want to update these documents when importing a new file (add new fields, replace old values with new ones) during the JSON file import process.
Previously, I was able to do this process in the process of importing a CSV file.
Code for CSV file:
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))
How can this be done with JSON?
JSON file like this:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为最好的方法是不要更新这些文档,而是要替换它们。
我假设您的日期字段可以用作唯一标识符。
不确定您的JSON文件是如何格式化的,但是如果将其格式化与模式相同的格式,则可以使用该文件,并使动态添加字段变得更容易,并利用Mongodbs结构更少的功能。
I think the best way to do this is to not update these documents but replace them.
I'm assuming your date fields can be used as unique identifiers.
Not sure how your json file is formatted but if it is formatted the same way as your schema this should work and make it easier to add fields dynamically and take advantage of MongoDBs structure less feature.
是的,确实如此,它的工作原理类似。可能对某人有用
Yes, exactly, it works in a similar way. Might be useful to someone