0

I would like some help with this code, I can't get a return through Pycharm, only if I open the container and run the command directly in mongosh.

My code:

connect = pymongo.MongoClient("mongodb://localhost:27017/")
base = connect["base_test"]
mycol = base["users"]
print(mycol.find())

<pymongo.cursor.Cursor object at 0x106177a60>

My docker-compose:

  mongo_db:
    image: mongo:latest
    ports:
      - 27017:27017
    volumes:
      - ./mongo_db:/data/db
    container_name: mongo_db

  mongo-express:
    image: mongo-express:latest
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://mongo_db:27017/
    container_name: mongo_express

in the mongo shell the call works:

base_test> db.users.find()
[ { _id: ObjectId("63498015bafdd447d73784fb"), name: 'Guilherme' } ]

my code in for:

connect = pymongo.MongoClient("mongodb://localhost:27017/")
base = connect["base_test"]
mycol = base["users"]
cur = mycol.find()
for doc in cur:
    print(doc)

Traceback (most recent call last):
  File "/PycharmProjects/SSE.py", line 12, in <module>
    for doc in mycol:
TypeError: 'Collection' object is not iterable

But in pymongo it's giving this cursor error, and when I put it inside for, it says it's not iterable. Help me please.

  • A `pymongo.cursor.Cursor` *should* be iterable, see [this answer as an example](https://stackoverflow.com/a/28970776/7867968). Can you show us the exact code you are using in the for loop that raises the exception? – C.Nivs Oct 14 '22 at 15:40
  • There is no error being shown here, you are simply printing out an object that doesn't have a particularly useful string representation. – jasonharper Oct 14 '22 at 15:41
  • I tried doing it this way and it didn't work either. – Guilherme Piccioni Oct 14 '22 at 15:53

1 Answers1

0

You have a typo; it should be:

for doc in cur:
    print(doc)
Belly Buster
  • 8,224
  • 2
  • 7
  • 20