简体   繁体   中英

How to connect mongoDB with python?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM