Outline
需要本地连接服务器MongoDB下载数据,结果由于数据库命名包含中横线“-”,导致无法连接数据库;
数据库名字示例:"stock-factor-staging"
解决
常规情况下我会这么连接MongoDB:
host = "192.168.xxx.xxx" port = 27017 user_name = 'xxx' user_pwd = 'xxxx' client = pymongo.MongoClient(host, port) db = client.data_futures.authenticate(user_name, user_pwd) # 指定数据库+登录认证 mydb = client["data_futures"] my_table = mydb["StkKLine"]
上面要连接的数据库是:data_futures,下划线连接;
可实际需要连接的库名为:"stock-factor-staging"
包含中横线,直接 db. 会报错;
后来发现还有一种写法,不用db.,直接db['db_name'] 即可:
host = "192.168.xxx.xxx" port = 27017 user_name = 'xxx-xxx' user_pwd = 'xxx' client = pymongo.MongoClient(host, port) db = client["stock-factor-staging"].authenticate(user_name, user_pwd) # 指定数据库 mydb = client["stock-factor-staging"] my_table = mydb["StkKLine"]
这样就OK了