如何在 pymongo 中更新/添加多个数据库?
公告板被刮擦并与Python Pymongo一起存放在MongoDB中。
如果数据丢失或进行更新,我们想添加数据,并且值不同。
我该怎么做?
以前的代码
b = dict(title=thread_title, url=thread_url, res=sorted(all_res))
collection.insert(b)
尝试代码
collection.update_one({"$set":{"title": thread_title}}, {"$set":{"url": thread_url}}, {"$set":{"res": sorted(all_res)}}, upsert=True)
错误代码
typeError collection.update_one()有多个值 'upsert'
大约有200个MongoDB文档。
_id 62459b8d6ebc7c7b3e14b3ad
字段:标题“线程标题”
字段:url“ urlurlurl”
字段:res Array 0“#100 2022/02/20 13:22评论等等等等等等” 1 “#101 2022/02/20 13:23评论等等等等”
The bulletin board is scraped and stored in MongoDB with Python pymongo.
We would like to add data if it is missing or update it if it exists and the values are different.
How can I do this?
Previous Code
b = dict(title=thread_title, url=thread_url, res=sorted(all_res))
collection.insert(b)
Trying Code
collection.update_one({"$set":{"title": thread_title}}, {"$set":{"url": thread_url}}, {"$set":{"res": sorted(all_res)}}, upsert=True)
Error Code
TypeError Collection.update_one() got multiple values for argument
'upsert'
There are about 200 MongoDB documents available.
_id 62459b8d6ebc7c7b3e14b3ad
field:title "THREAD TITLE"
field:url "URLURLURL"
field:res Array 0 "#100 2022/02/20 13:22 comment blah blah blah" 1
"#101 2022/02/20 13:23 comment blah blah blah"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
mongo更新官方文档
在你的更新查询中缺少过滤器部分:
上述查询将更新您集合中 id = 62459b8d6ebc7c7b3e14b3ad 的文档
mongo update official document
In your update query the filter part is missing:
The above query will update the document with id = 62459b8d6ebc7c7b3e14b3ad in your collection
如果您尝试“分离”行代码,您将看到您为函数提供了 4 个参数,您提供的每个参数都是一个参数,因此
upsert
将作为值{"$ set":{"res":sorted(all_res)}}
,你不应该分离'update'参数除此之外,update_one函数采用一个过滤器(它不是一个可选参数,你应该总是给一个过滤器)。
还有 update_one 函数的定义
最后,如果您想同时更新多个实例,您应该考虑 update_many 函数(它的工作方式基本上与 update_one 相同)。
这段代码应该可以工作,并且记住添加一个过滤器。
If you try to 'separate' your line code, you will see that you're giving the function 4 arguments, each set you gave is an argument so
upsert
is taking as value{"$set":{"res": sorted(all_res)}}
, you shouldn't separate the 'update' argumentIn addition to that, the update_one function take a filter (it's not an optional argument, you should always give a filter).
There is the definition of the update_one function
And finally, if you want to update multiple instances at the same time you should consider update_many function (it basically works the same way as update_one).
This code should work, and remember to add a filter.