mongo搭建的是副本集结构(Replica Sets),副本集当前状态如下:
>>> con.database_names()
[u'test', u'local']
>>> db = con.test
>>> db.collection_names()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/pymongo/database.py", line 408, in collection_names
names = [r["name"] for r in results]
File "/usr/local/lib/python2.7/site-packages/pymongo/cursor.py", line 904, in next
if len(self.__data) or self._refresh():
File "/usr/local/lib/python2.7/site-packages/pymongo/cursor.py", line 848, in _refresh
self.__uuid_subtype))
File "/usr/local/lib/python2.7/site-packages/pymongo/cursor.py", line 800, in __send_message
self.__uuid_subtype)
File "/usr/local/lib/python2.7/site-packages/pymongo/helpers.py", line 98, in _unpack_response
raise AutoReconnect(error_object["$err"])
pymongo.errors.AutoReconnect: not master and slaveOk=false
报错了吧
“not master and slaveOk=false",提示当前连接的不是主节点,需要设定slaveOK=false才能调用
那么接下有两个路径可以解决该问题,找到主节点,发现是(172.29.1.75)
重新连接一遍吧。。。
>>> con = pymongo.Connection('172.29.1.75',27017)
>>> db = con.test
>>> collection = db.collection_names() # 不报错了
>>> collection
[u'testdb', u'system.indexes']
>>> db.testdb.find_one()
{u'test1': u'testval1', u'_id': ObjectId('53057f1b8dec7b40dc644bc1')}
>>> db.testdb.insert({"test2":"testval2"})
ObjectId('5305b2db2aa340271df3e0f8')
>>> for test_value in db.testdb.find():
... test_value
...
{u'test1': u'testval1', u'_id': ObjectId('53057f1b8dec7b40dc644bc1')}
{u'test2': u'testval2', u'_id': ObjectId('5305b2db2aa340271df3e0f8')}
>>>
咱们先插入两条用户数据
>>> db.testdb.insert({"name": "Tim", "age": 18})
ObjectId('5305b3e72aa340271df3e0f9')
>>> db.testdb.insert({"name": "Rose", "age": 19})
ObjectId('5305b3fa2aa340271df3e0fa')
接着查询age=19的用户
>>> db.testdb.find_one({"age":19})
{u'age': 19, u'_id': ObjectId('5305b3fa2aa340271df3e0fa'), u'name': u'Rose'}
或者雄浑name=Tim的用户
>>> db.testdb.find_one({"name":"Tim"})
{u'age': 18, u'_id': ObjectId('5305b3e72aa340271df3e0f9'), u'name': u'Tim'}
>>> db.testdb.count()
4
mongo shell显示,确实有4条数据
replset:PRIMARY> db.testdb.find()db.testdb.find()
{ "_id" : ObjectId("53057f1b8dec7b40dc644bc1"), "test1" : "testval1" }
{ "_id" : ObjectId("5305b2db2aa340271df3e0f8"), "test2" : "testval2" }
{ "_id" : ObjectId("5305b3e72aa340271df3e0f9"), "age" : 18, "name" : "Tim" }
{ "_id" : ObjectId("5305b3fa2aa340271df3e0fa"), "age" : 19, "name" : "Rose" }
未完待续。。。。。