Reputation: 517
I have the string s = "users.count()"
and the db
object.
How do I combine db
and s
such that print combination(db,s)
prints the total number of users?
I tried db[s]
and db+s
and both don't work.
Thanks!
Upvotes: 1
Views: 704
Reputation: 6729
Check the docs
1) Initialize your connection first
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
2) Select your db
db = client["db_name"] #replace db_name with your database name
3) Run count()
on your collection. Say, your collection name is users
print db.users.count()
# OR
print db["users"].count()
If you have something like s = "users.count()"
and want to execute s
. Try:
collection = s.split(".")[0]
function_call = s.split(".")[-1].strip("()")
print getattr(db[collection],function_call)()
Upvotes: 1