从MLab迭代pymongo游标



为什么光标不迭代?我确信应该有一个简单的解决办法。

我已经尝试了多个堆栈溢出的答案和Mongodb的文档https://docs.mongodb.com/getting-started/python/query/

代码如下:

from pymongo import MongoClient
#Connect to Mongo Client 
client = MongoClient('mongodb://the_username:the_password@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used
# Define Collection
collection = db.posts
print collection
结果:

Collection(Database(MongoClient(host=['ds047124.mlab.com:47124'], document_class=dict, tz_aware=False, connect=True), u'politicians_from_theage'), u'posts')

则光标将打印其位置:

# Define Cursor
my_cursor = collection.find()
print my_cursor 
结果:

<pymongo.cursor.Cursor object at 0x0000000003247518>

然后尝试遍历游标提供一个超时:

 # Perform query 
    cursor = db.posts.find()
    #Iterate the cursor and print the documents.
for document in cursor:
    print(document)  #No Luck

回溯错误或迭代:

Traceback (most recent call last):
  File "C:PythonCPythonWebScraping17_MongoInterfacemongoget.py", line 18, in <module>
    for result_object in my_cursor:
  File "C:Python27libsite-packagespymongocursor.py", line 1090, in next
    if len(self.__data) or self._refresh():
  File "C:Python27libsite-packagespymongocursor.py", line 1012, in _refresh
    self.__read_concern))
  File "C:Python27libsite-packagespymongocursor.py", line 850, in __send_message
    **kwargs)
  File "C:Python27libsite-packagespymongomongo_client.py", line 827, in _send_message_with_response
    server = topology.select_server(selector)
  File "C:Python27libsite-packagespymongotopology.py", line 210, in select_server
    address))
  File "C:Python27libsite-packagespymongotopology.py", line 186, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: ds047124.mlab.com:47124: timed out

我试过迭代'cursor', 'my_cursor'和'collection',每个都提供了服务器超时的回溯错误。

这可能对你有帮助:-

 # Perform query 
cursor = db.posts.find().toAray(function(err, result){
     #Iterate the cursor and print the documents.
     for document in result:
     print(document);
}) //Will give you array of objects.

找到了答案,我专注于游标,而不是从游标从JSON加载对象到JSON列表。

最终代码如下(删除URI)

import json
from datetime import date, timedelta
from pymongo import MongoClient
from bson import json_util
#Connect to Mongo Client 
client = MongoClient('mongodb://user:pword@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used
print db
# Define Collection
collection = db.posts
print collection # print Collection(Database(MongoClient(host=['ds047124.mlab.com:47124']...

cursor = collection.find()
print cursor
# Obtain json 
json_docs = []
for doc in cursor:
    json_doc = json.dumps(doc, default=json_util.default)
    json_docs.append(json_doc)
print json_docs #json result
# List Comprehension version
#json_docs = [json.dumps(doc, default=json_util.default) for doc in cursor]
#To get back from json again as string list
docs = [json.loads(j_doc, object_hook=json_util.object_hook) for j_doc in json_docs]
print docs
print 'kitty terminates program'

试试这个:

cursor = db.posts.find()
for document in list(cursor):
    print(document) 

最新更新