[英]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? 如何将
db
和s
组合在一起, 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.