|
发表于 2023-7-5 09:53:49
|
显示全部楼层
在 MongoDB 中,当你创建数据库连接并指向一个不存在的数据库(在你的例子中是 "test")时,MongoDB 不会立即在物理存储上创建这个数据库。数据库将只在内存中被引用,但在你向该数据库写入数据之前,不会在磁盘上创建相应的文件。
所以,尽管你的 Python 代码没有出现错误,你在 MongoDB Compass 中看不到 "test" 数据库,这是正常的。一旦你在 "test" 数据库中创建一个集合并插入一些数据,你应该就能在 MongoDB Compass 中看到这个数据库了。
这里有一个创建集合并插入数据的例子:
- import pymongo
- client = pymongo.MongoClient(host='localhost', port=27017)
- db = client.test
- collection = db['my_collection']
- post = {"author": "Mike", "text": "My first blog post!"}
- collection.insert_one(post)
复制代码
在运行了这段代码之后,你就可以在 MongoDB Compass 中看到 "test" 数据库以及它包含的 "my_collection" 集合了。 |
|