问题
I have a query which is as below:
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
refers to the collection in the class. If limit
parameter is set I need to bind limit()
pymongo
function to the query.
NB: the limit is just a sample case it could be any function like sort
, etc. So I just want to know is there a mechanism to bind params like this?
回答1:
Do you mean like this?:
def get_data(self, limit=None):
cursor = self.collection.find(condition)
if limit is not None:
return cursor.limit(limit)
else:
return cursor
回答2:
below 2 queries return same results
self.collection.find()
self.collection.find().sort([("$natural", pymongo.ASCENDING)])
Sort Natural Order
and also below 2 queries return same results
self.collection.find()
self.collection.find().limit(0)
A limit of 0
is equivalent to no limit. source
so you can combine these and write a single line query as follows
self.collection.find().limit(self.limit or 0).sort(self.sort or [("$natural", pymongo.ASCENDING)])
If you have set values for limit/sort they will be applied otherwise will be ignored.
来源:https://stackoverflow.com/questions/46788207/is-there-a-way-to-bind-another-function-like-limit-to-pymongo-query-based-on-c