1

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!

2
  • too less information Commented Sep 17, 2014 at 5:43
  • what more information do you need? Commented Sep 17, 2014 at 5:54

1 Answer 1

1

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)()
Sign up to request clarification or add additional context in comments.

3 Comments

The constraint is to use the string "users.count()" and convert that into db.users.count() i know that i can just use the command directly. I am programmatically generating commands so i need to be able to use variable strings to build up a command
i eventually used an ugly if elif elif elif chain but im hoping theres something better
hmm interesting wouldn't have thought to do this ha ill try it out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.