0

I'm calling function with argument value database name. When I print argument other function it's working properly but when i'm connecting this argument value with database it's not giving any output

My code is Here.

def myFunction(mydb):
    from pymongo import MongoClient
    print(mydb)
    client = MongoClient('localhost:27017')
    db = client.mydb
    data = db.collection.find().count()
    return data

mydb = 'my_databaseName'
myFunction(mydb);

when I work with the above code it's returning:

Oputput:0

But when I'm working with this code it's working properly

 def myFunction(mydb):
        from pymongo import MongoClient
        print(mydb)
        client = MongoClient('localhost:27017')
        db = client.my_databaseName #its static database name
        data = db.collection.find().count()
        return data

So how can I solve this problem?

1
  • yes, collection is existing in my database. Commented Feb 2, 2016 at 12:02

2 Answers 2

2

You need to fetch the database directly, as its passed into your method:

from pymongo import MongoClient
client = MongoClient('localhost:27017')

def my_function(mydb):
    db = client.get_database(mydb)
    return db.collection.find().count()

print(my_function('my_database'))
Sign up to request clarification or add additional context in comments.

Comments

0

https://github.com/mak705/Python_Mongo_Basics/blob/master/Python_Mongo_Basics.ipynb

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]

dblist = myclient.list_database_names()
if "mydatabase" in dblist:
  print("The database exists.")

#Create a collection called "customers":
mycol = mydb["customers"]
print(mydb.list_collection_names())

Comments

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.