Is there a way to bind another function like limit() to pymongo query based on condition?

孤人 提交于 2019-12-11 05:53:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!