草庐IT

python - 写入时出现pymongo错误

coder 2023-08-18 原文

我无法对远程 mongodb 数据库进行任何写入。我能够连接并进行查找(例如查找)。我这样连接:

conn = pymongo.MongoClient(db_uri,slaveOK=True)
db = conn.test_database
coll = db.test_collection

但是当我尝试插入时,

coll.insert({'a':1})

我遇到了一个错误:

---------------------------------------------------------------------------
AutoReconnect                             Traceback (most recent call last)
<ipython-input-56-d4ffb9e3fa79> in <module>()
----> 1 coll.insert({'a':1})

/usr/lib/python2.7/dist-packages/pymongo/collection.pyc in insert(self, doc_or_docs, manipulate, safe, check_keys, continue_on_error, **kwargs)
    410             message._do_batched_insert(self.__full_name, gen(), check_keys,
    411                                        safe, options, continue_on_error,
--> 412                                        self.uuid_subtype, client)
    413 
    414         if return_one:

/usr/lib/python2.7/dist-packages/pymongo/mongo_client.pyc in _send_message(self, message, with_last_error, command, check_primary)
   1126             except (ConnectionFailure, socket.error), e:
   1127                 self.disconnect()
-> 1128                 raise AutoReconnect(str(e))
   1129             except:
   1130                 sock_info.close()

AutoReconnect: not master

如果我删除 slaveOK=True(将其设置为默认值 False),我仍然可以连接,但读取(和写入)失败:

AutoReconnect                             Traceback (most recent call last)
<ipython-input-70-6671eea24f80> in <module>()
----> 1 coll.find_one()

/usr/lib/python2.7/dist-packages/pymongo/collection.pyc in find_one(self, spec_or_id, *args, **kwargs)
    719                            *args, **kwargs).max_time_ms(max_time_ms)
    720 
--> 721         for result in cursor.limit(-1):
    722             return result
    723         return None

/usr/lib/python2.7/dist-packages/pymongo/cursor.pyc in next(self)
   1036             raise StopIteration
   1037         db = self.__collection.database
-> 1038         if len(self.__data) or self._refresh():
   1039             if self.__manipulate:
   1040                 return db._fix_outgoing(self.__data.popleft(),

/usr/lib/python2.7/dist-packages/pymongo/cursor.pyc in _refresh(self)
    980                               self.__skip, ntoreturn,
    981                               self.__query_spec(), self.__fields,
--> 982                               self.__uuid_subtype))
    983             if not self.__id:
    984                 self.__killed = True

/usr/lib/python2.7/dist-packages/pymongo/cursor.pyc in __send_message(self, message)
    923                                                 self.__tz_aware,
    924                                                 self.__uuid_subtype,
--> 925                                                 self.__compile_re)
    926         except CursorNotFound:
    927             self.__killed = True

/usr/lib/python2.7/dist-packages/pymongo/helpers.pyc in _unpack_response(response, cursor_id, as_class, tz_aware, uuid_subtype, compile_re)
     99         error_object = bson.BSON(response[20:]).decode()
    100         if error_object["$err"].startswith("not master"):
--> 101             raise AutoReconnect(error_object["$err"])
    102         elif error_object.get("code") == 50:
    103             raise ExecutionTimeout(error_object.get("$err"),

AutoReconnect: not master and slaveOk=false

我连接不正确吗?有没有办法指定连接到主副本?

最佳答案

AutoReconnect: not master意味着您的操作失败,因为您尝试在其上发出命令的节点不是副本集的主节点,其中命令(例如,写操作)要求该节点是主节点。设置slaveOK=True只是使您能够从辅助节点读取,默认情况下您只能从主节点读取。

如果使用 replicaSet=<replica set name> 向构造函数提供副本集名称,MongoClient 会自动发现并连接到主节点。 .请参阅 Connecting to a Replica Set 中的“PyMongo docs” .

顺便说一句,slaveOK已弃用,替换为 ReadPreference .如果您想将主节点以外的节点作为目标,则可以在创建客户端或发出查询时指定 ReadPreference。

关于python - 写入时出现pymongo错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25861174/

有关python - 写入时出现pymongo错误的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  3. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  4. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  5. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  8. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  9. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  10. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

随机推荐