1

When using a cursor to iterate through a collection like so,

import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
for item in cursor:
    print item
    #this will print the item as a dictionary

only the values are returned. I'm looking for a way to access the name of the value.

I have found a similar method called getCollectionNames() however it is used to return every collection name in the database.


Quick [Hacky] Fix: Store the name of the collection inside the collection itself and simple call the name from the value returned by the cursor using item.name

2 Answers2

1

If I understand correctly, you are looking for a way to get the collection name you are working on or that you have queried; If that is the case here is how you do it: user collection.name

import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
print cursor.collection.name
for item in cursor:
    print item
    #this will print the item as a dictionary

If you mean to retrieve the keys inside of the collection itself. You can simply add an extra loop and retrieve the keys for each document in cursor. example:

import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
print cursor.collection.name
for item in cursor:
    for key in item:
        print key
ibininja
  • 1,209
  • 1
  • 15
  • 29
0

You can iterate over the top level field names and their associated values using this snippet:

for fieldname, fieldvalue in item.iteritems():
   print (fieldname, fieldvalue )
Alex
  • 21,273
  • 10
  • 61
  • 73
  • Thanks for responding so quickly. I came across this [solution](http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python) prior to posting this question but I immediately discarded it since _iteritems()_ is a method for dictionary objects and it wasn't listed [here](http://api.mongodb.org/python/current/api/pymongo/cursor.html) under the methods applicable to cursor objects – user3720570 Jan 27 '16 at 00:40
  • Cursor objects are simply nested dictionaries or at least can be treated as such. – Alex Jan 27 '16 at 07:30