有没有办法根据条件将另一个函数(如 limit() )绑定到 pymongo 查询? [英] Is there a way to bind another function like limit() to pymongo query based on condition?

查看:23
本文介绍了有没有办法根据条件将另一个函数(如 limit() )绑定到 pymongo 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,如下所示:

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 指的是类中的集合.如果 limit 参数是 set 我需要将 limit() pymongo 函数绑定到查询.

self.collection refers to the collection in the class. If limit parameter is set I need to bind limit() pymongo function to the query.

注意: 限制只是一个示例,它可以是任何函数,例如 sort 等.所以我只想知道是否有一种机制来绑定参数,例如这个?

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?

推荐答案

以下 2 个查询返回相同的结果

below 2 queries return same results

self.collection.find()
self.collection.find().sort([("$natural", pymongo.ASCENDING)])

自然顺序排序

还有以下 2 个查询返回相同的结果

and also below 2 queries return same results

self.collection.find()
self.collection.find().limit(0)

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.

这篇关于有没有办法根据条件将另一个函数(如 limit() )绑定到 pymongo 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆