[英]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 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.