pythondatabasemongodbcollectionspymongo

Access a MongoDB Collection Using String in PyMongo


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)


Solution

  • 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)