Suppose I specify a MongoDB cursor with pymongo
, which DOES NOT include all fields in the result set like this:
from pymongo import MongoClient
conn = MongoClient('mongodb://localhost:27017')
cur = conn['my_db']['my_collection'].find({},{'_id' : 0, 'my_unwanted_field' : 0})
Is there a function or attribute that will return me the names of the fields present in cur
.
Something equivalent on Mongo Shell using findOne
would be:
> var cur = findOne({},{'_id' : 0, 'my_unwanted_field' : 0})
> Object.keys(cur)
["field_1", ... , "field_n"]
Keys in JS objects must be unique.
dir() To list all the attributes of an object, use the built-in dir() function. It returns a long list of attribute names, that is, method and variable names of the object. There is a bunch of automatically generated attributes in any Python class.
To print the attributes of an object we can use “object. __dict__” and it return a dictionary of all names and attributes of object. After writing the above code (python print object attributes), once you will print “x. __dict__” then the output will appear.
Use a loop to iterate the cursor object, then use .keys()
to get the keys of any regular python dict, which seems like this:
for item in cur:
print item.keys()
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