下面的代码让我更容易使用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)
你的代码和它将要得到的一样高效,因为cursor_result
总是由一个分支设置的,所有实际工作都在其中完成。唯一的问题是它有很多重复的代码。您可以通过一次处理一个选项来分解它。
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)