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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With