如何使用pymongo构造变量查询



我有字符串s = "users.count()"

以及CCD_ 2对象。

如何组合dbs,使print combination(db,s)打印用户总数?

我试过db[s]db+s,但都不起作用。

谢谢!

检查文档
1) 首先初始化您的连接

from pymongo import MongoClient
client = MongoClient('localhost', 27017)

2) 选择您的db

db = client["db_name"] #replace db_name with your database name

3) 对您的收藏运行count()。比方说,你的收藏名称是users

print db.users.count()
# OR
print db["users"].count()

如果您有类似s = "users.count()"的东西,并且想要执行s。尝试:

collection = s.split(".")[0]
function_call = s.split(".")[-1].strip("()")
print getattr(db[collection],function_call)()

最新更新