Skip to content

Instantly share code, notes, and snippets.

@k0emt
Last active December 13, 2015 22:18
Show Gist options
  • Save k0emt/4983348 to your computer and use it in GitHub Desktop.
Save k0emt/4983348 to your computer and use it in GitHub Desktop.
Utility code to get the keys from a document in a specified MongoDB database and collection.
#!/usr/local/bin/python
import sys
from pymongo import MongoClient
if len(sys.argv) < 3:
print 'usage is: ' + sys.argv[0] + ' databaseName collectionName'
sys.exit()
dbName = sys.argv[1]
collectionName = sys.argv[2]
print 'Database: ' + dbName + ' Collection: ' + collectionName
connection_string = "mongodb://localhost"
connection = MongoClient(connection_string, safe=True)
db = connection[dbName]
collection = db[collectionName]
document = collection.find_one()
if document is not None:
print 'document keys: '
print document.keys()
else:
print '*** No Document Found ***'
connection.disconnect()
@k0emt
Copy link
Author

k0emt commented Feb 19, 2013

Note that this only gets the top level keys -- it doesn't delve into subdocuments.
On the command line give the utility the name of the database and the collection name you want examined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment