python - 写入时出现pymongo错误

标签 python mongodb pymongo

我无法对远程 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 - 用于同时过滤和转换的列表理解中的中间变量

python - 在 Pycharm 上使用 pyplot 绘制图形时出现 "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure."

python - pymongo (python+mongodb) 删除集合/gridfs?

python - Pymongo 在 27017 一直拒绝连接

相当于 "find -type f"的 Python

python - 从 pytest_generate_tests 中排除测试

mongodb - 项目值作为键,嵌入文档作为 mongo 中的值

mongodb - 数据库复合索引最佳实践 Mongodb

python - python3 flask 应用程序中的 pymongo 导入错误

python - 如何在 mongoengine 中使用有序 false 进行批量插入