PyMongo遊標逾時問題

來源:互聯網
上載者:User

問題描述:

用PyMongo串連Mongodb資料庫進行查詢操作時,當查詢的資料集比較大,需要維持一個時間較長的串連,如果不做設定,就會造成crusor time out。

解決方案:

import pymongo, datetimedef readInstance():    print 'Read instances ...'    global conn_mongo        db = conn_mongo['mongo_db']    col_query = db['query']        try:        #在find函數中設定不會逾時        for item in col_meta.find(query, timeout=False).sort("_id", pymongo.ASCENDING):            print item['_id'] #便利業務過程,此過程因為資料集很大而時間很長    except:        errinfo = sys.exc_info()        print errinfo    finally:        #一定要在使用完之後釋放串連,不然會一直佔用系統資源        conn_mongo.close()        if __name__ == '__main__':    start_ms = datetime.datetime.now()        mongo_host = '192.168.4.81'    mongo_port = 27017    conn_mongo = pymongo.Connection(mongo_host, mongo_port)        readInstance()        end_ms = datetime.datetime.now()    print 'cost: ' + str((end_ms - start_ms).seconds) + ' s'    pass

主要就是在find函數執行時指定timeout=False,並且記住在使用完之後釋放串連。

Good Luck

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.