I am attempting to store the name of a MongoDB collection in a variable and refer to that in a query. If I specify the name of the collection without quotes, my query runs, but if I place the name of my collection in a variable as a string, my query will not run.
Here is what I am trying to run. As mentioned, when "x" is replaced with P38, the query produces results, but does not produces results in its current form.
x = 'P38'
cursor = db.x.find({})
for item in cursor:
print(item)
3
Answers
Well, your X variable is a string. It’s not a MongoDB collection object.
When you call X.find() you’re actually executing .find() method from string object, not from your DB collection, which will result in TypeError, because string’s .find() method expects substring, not empty dictionary.
If you need to query results from MongoDB, you should use your MongoDB object without converting it to Python string object. Python has no way to recognize what you mean by doing this, it treats this object as a string and doesn’t care if this string’s value is equal to your MongoDB object class name.
What are you trying to achieve with this?
Use
get_collection()
as:When you do
db.x.find({})
Mongo will usex
as the collection name. It will not replace the "value of x" in usages likedb.x.find
becausex
is used an attribute ofdb
.db.x
is equivalent todb.get_collection("x")
, note the quotes.x
is the collection name, not a variable.So if you wanted
db.get_collection("P38")
, it needs to bedb.P38
or use the variablex
in the long form –>db.get_collection(x)
When you get
Collection
s that way, you use direct attribute lookup. Direct attribute lookup must be done the right way (i.e., as direct attribute lookup):None of this is necessary since
Database.__getattr__()
[github] (i.e., it’s dunder method for attribute lookup) uses dictionary lookup up under the hood (it uses the dunder methodDatabase.__getitem__()
[github]).I would just access each
Collection
from aDatabase
using dictionary lookup.This is just my preference. You can still do attribute lookup the way you want using my example below:
[1] Remember to use a default when getting an attribute to avoid raising an
AttributeError
exception.