skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. Use get_collection() as:

    x = 'P38'
    
    collection = db.get_collection(x)
    cursor = collection.find({})
    
    # or directly
    cursor = db.get_collection(x).find({})
    

    When you do db.x.find({}) Mongo will use x as the collection name. It will not replace the "value of x" in usages like db.x.find because x is used an attribute of db.

    db.x is equivalent to db.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 be db.P38 or use the variable x in the long form –> db.get_collection(x)

    Login or Signup to reply.
  3. When you get Collections that way, you use direct attribute lookup. Direct attribute lookup must be done the right way (i.e., as direct attribute lookup):

    db.P38

    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 method Database.__getitem__() [github]).

    I would just access each Collection from a Database using dictionary lookup.

    db["P38"]

    This is just my preference. You can still do attribute lookup the way you want using my example below:

    col = getattr(db, "P38", None) #[1]
    if col:
        #•••Rest of code•••

    [1] Remember to use a default when getting an attribute to avoid raising an AttributeError exception.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search