Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all fields of a document in pyMongo

I want to find all the fields of a document using pymongo for performing retrieving data from them. The code below is giving all the documents with its all fields. But can we find all fields or keys of a document?

f = db['Collection'].find()
for i in f:
    print(i['Date'])

I can get all the documents ObjectId from

print(db['Collection'].distinct("_id"))

Now we have ids of all documents. Can we find fields?

like image 723
Amar Avatar asked Oct 19 '22 01:10

Amar


1 Answers

The PyMongo find() method returns a Cursor instance, which allows you to iterate over all matching documents. The documents in your iteration is a Python Dictionary, so you can list all of its keys using keys() method, for example:

cursor = db['collection'].find({})
for document in cursor: 
    print(document.keys())  # print all fields of this document. 

Having said the above, generally you should know the fields in your collection. If you want to query documents that contain certain fields see operator $exists.

like image 186
Wan Bachtiar Avatar answered Nov 15 '22 14:11

Wan Bachtiar