下面的代码使我更容易使用Pymongo。
但是我试图对其进行重构,因为我认为它的效率太低。
由于我是初学者,因此我尝试了几次,但对它不满意,因此我需要一些建议。
对不起,代码混乱。只要参考它,
,请告诉我是否有任何库或简单示例。谢谢!
def find_(self, collection, find_value=None, projection=None, sort=None, skip=None, limit=None, multi_array=None, cursor=False):
if sort is None:
if skip is None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection)
if skip is not None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).skip(skip)
if skip is None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).limit(limit)
if skip is not None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).skip(skip).limit(limit)
else:
arg = tuple((key, val) for key, val in sort.items())
if skip is None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg)
if skip is not None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).skip(skip)
if skip is None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).limit(limit)
if skip is not None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).skip(skip).limit(limit)
答案 0 :(得分:2)
您的代码将尽可能高效,因为cursor_result
始终仅由一个分支设置,在该分支中完成了所有实际工作。唯一的问题是它有 lot 个重复的代码。您可以通过一次处理每个选项将其排除在外。
def find_(self, collection, find_value=None, projection=None, sort=None, skip=None, limit=None, multi_array=None, cursor=False):
# Get the right path and call find
cursor_result = self.db_path[collection].find(find_value, projection)
# Sort if necessary
if sort is not None:
cursor_result = cursor_result.sort(tuple(sort.items()))
# Skip if necessary
if skip is not None:
cursor_result = cursor_result.skip(skip)
# Limit if necessary
if limit is not None:
cursor_result = cursor_result.limit(limit)