Skip to content Skip to sidebar Skip to footer

Is There A Way To Bind Another Function Like Limit() To Pymongo Query Based On Condition?

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.collec

Solution 1:

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 or0).sort(self.sortor [("$natural", pymongo.ASCENDING)])

If you have set values for limit/sort they will be applied otherwise will be ignored.

Solution 2:

Do you mean like this?:

defget_data(self, limit=None):
    cursor = self.collection.find(condition)
    if limit isnotNone:
        return cursor.limit(limit)
    else:
        return cursor

Post a Comment for "Is There A Way To Bind Another Function Like Limit() To Pymongo Query Based On Condition?"