Consult MongoDB from Python

2

I'm trying to make a query to MongoDB from Python, I'm just getting into these technologies.

I have this code

import pymongo
from pymongo import MongoClient

client = MongoClient()
db = client.crawler.users
res = db.find()

print( res )

I get this message:

<pymongo.cursor.Cursor object at 0x7f438d574cd0>
Process exited with code: 0

I was expecting a response like that since from the Mongo console if you execute it:

> db.users.find()
{ "_id" : ObjectId("5b3fd50706dd45b669417454"), "NAME" : "FOO", "LAST_NAME" : "BAR" }
{ "_id" : ObjectId("5b3fdd2e613d0b159da70742"), "NAME" : "POO", "LAST_NAME" : "MAR" }

I appreciate your patience

    
asked by Alberto Siurob 07.07.2018 в 00:17
source

1 answer

2

What happens is that you are printing the cursor. According to the documentation, the method find returns an instance of pymongo.cursor.Cursor . To print the documents you have to iterate the cursor:

import pymongo
from pymongo import MongoClient

client = MongoClient()
db = client.crawler.users
res = db.find()
for document in res:
    print(document)

With that you should see the content of each document in the collection. It looks better if you use pprint :

import pymongo
from pymongo import MongoClient
from pprint import pprint

client = MongoClient()
db = client.crawler.users
res = db.find()
for document in res:
    pprint(document)
    
answered by 07.07.2018 / 00:26
source