Python 有没有办法根据条件将另一个函数(如limit()绑定到pymongo查询?
我有一个问题如下:Python 有没有办法根据条件将另一个函数(如limit()绑定到pymongo查询?,python,pymongo,Python,Pymongo,我有一个问题如下: def get_data(self, limit=None): # I just want to add limit() in case it is set, not otherwise self.collection.find(condition) self.collection指类中的集合。如果limit参数为set我需要将limit()pymongo函数绑定到查询 NB:限制只是一个示例,它可以是任何函数,如排序,等等。所以我只想知道是否有一种机制可以
def get_data(self, limit=None):
# I just want to add limit() in case it is set, not otherwise
self.collection.find(condition)
self.collection
指类中的集合。如果limit
参数为set我需要将limit()
pymongo
函数绑定到查询
NB:限制只是一个示例,它可以是任何函数,如
排序
,等等。所以我只想知道是否有一种机制可以像这样绑定参数?你的意思是这样吗?:
def get_data(self, limit=None):
cursor = self.collection.find(condition)
if limit is not None:
return cursor.limit(limit)
else:
return cursor
下面两个查询返回相同的结果
self.collection.find()
self.collection.find().sort([("$natural", pymongo.ASCENDING)])
self.collection.find()
self.collection.find().limit(0)
下面两个查询返回相同的结果
self.collection.find()
self.collection.find().sort([("$natural", pymongo.ASCENDING)])
self.collection.find()
self.collection.find().limit(0)
0
的限制相当于没有限制
因此,您可以将它们结合起来,编写一个单行查询,如下所示
self.collection.find().limit(self.limit or 0).sort(self.sort or [("$natural", pymongo.ASCENDING)])
如果您为限制/排序设置了值,则将应用这些值,否则将被忽略。是,但是现在,如果您必须在
limit
之后添加另一个函数,如sort
,它会是什么样子?传递$natural时,您应该注意使用索引:索引使用包含按$natural排序顺序的查询不要使用索引来实现查询谓词,但以下情况除外:如果查询谓词是相等的条件{u id:},则具有sort by$natural order的查询可以使用{u id索引。