mongodb PyMongo和Docker-Compose;无法插入文档

qhhrdooz  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(128)

尝试使用MongoDB服务器将测试文档插入到Python中的测试集合中。
docker-compose.yml(直接来自https://hub.docker.com/_/mongo上的文档)

# Use root/example as user/password credentials
version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

python(直接来自https://pymongo.readthedocs.io/en/stable/tutorial.html上的文档)

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient('mongodb://root:example@localhost:27017/')

# Connect to database
db = client['test']

# Connect to collection
collection = db['test']

# Insert document
collection.insert_one({"name": "John", "age": 30})

print("test complete")

我已经运行了docker-compose,并成功地查看了mongo-express服务器的内容。我使用调试器逐步完成了每个部分,它在collection. insert上停止。我哪里做错了?谢谢!

hi3rlvi2

hi3rlvi21#

我只是想补充一下

ports:
      - 27017:27017

到docker-compose,它现在成功插入:)

相关问题