简体   繁体   English

如何使用pymongo构造变量查询

[英]How do I construct a variable query with pymongo

I have the string s = "users.count()" 我有字符串s = "users.count()"

and the db object. db对象。

How do I combine db and s such that print combination(db,s) prints the total number of users? 如何将dbs组合在一起, s使print combination(db,s)打印出用户总数?

I tried db[s] and db+s and both don't work. 我尝试了db[s]db+s ,但都没有用。

Thanks! 谢谢!

Check the docs 检查文档
1) Initialize your connection first 1)首先初始化您的连接

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

2) Select your db 2)选择您的db

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

3) Run count() on your collection. 3)在您的集合上运行count() Say, your collection name is users 假设您的收藏名称是users

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

If you have something like s = "users.count()" and want to execute s . 如果您有类似s = "users.count()"并想要执行s Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM