如何在本地连接时指定mongo数据库



我有一个名为test的本地数据库,其中有一个称为posts的集合。

以下内容适用于

client = MongoClient('mongodb://localhost:27017/')
db = client.test
collection = db.list_collection_names()

然而,当我试图在mongo-uri中指定数据库时,我得到了一个错误

test_db = MongoClient('mongodb://localhost:27017/test')
collection = test_db.list_collection_names()
TypeError: 'Database' object is not callable. If you meant to call the 'list_collection_names' method on a 'MongoClient' object it is failing because no such method exists.

如何直接在uri中指定数据库?

使用mongodb://localhost:27017/test,您仍然只是连接到mongodb实例,但在连接中指定了一个默认数据库。您没有直接连接到test数据库。

client = MongoClient('mongodb://localhost:27017/test')
dbs = client.list_database_names()
print(dbs) #['admin', 'config', 'local', 'test']

要访问uri中的默认数据库,请执行

client = MongoClient('mongodb://localhost:27017/test')
db = client.get_database()
collection = db.list_collection_names()

最新更新