pymongo 游标需要很长时间才能找到

pymongo cursor taking long time to find

Pymongo 游标耗时约 2 秒,请提出优化以下查询的方法。

查询事实

Records in MongoDB : 120,000
Indexed Key: emp_id
MongoDB Server: 3.2.11
PyMongo       : 3.5
Python        : 2.7

光标

要从数据库中查找文档,通过使用索引字段作为过滤器并仅投影必填字段,耗时约 2 秒。

我正在寻找优化此查询的方法,以使其更快。

db = client["db_name"]
user_data = db.collection_name.find_one(
    {"emp_id": 1234}, {'nameFirst': 1, 'nameLast': 1, 'emp_id': 1, }
)

已用时间:1.829226017


出于参考目的,请使用 find() 参考相同的查询

def query_cursor():
    db = client["db_name"]
    cursor = db.collection_name.find(
        {"emp_id": 1234}, {'nameFirst': 1, 'nameLast': 1, 'emp_id': 1, }
    ).limit(1)

    return cursor

def get_user_data():
    cursor = query_user_data()
    user_data = None
    for document in cursor:
        user_data = document
    return user_data

print(get_user_data())

query_cursor 的运行时间:0.00215888023376

get_user_data 的运行时间:1.79128599167

切换到正确的数据中心后问题已解决。现在数据库查询运行速度超快,不到 0.10 秒。