Vandexel
Vandexel

Reputation: 639

MongoDB PyMongo Listing all keys in a document

I have a question about how to manipulate a document in PyMongo to have it list all of its current keys, and I'm not quite sure how to do it. For example, if I had a document that looked like this:

{
    "_id" : ObjectID("...")
    "name": ABCD,
    "info": {
        "description" : "XYZ",
        "type" : "QPR"
    }
}

and I had a variable "document" that had this current document as its value, how could I write code to print the three keys:

"_id"
"name"
"info"

I don't want it to list the values, simply the names. The motivation for this is that the user would type one of the names and my program would do additional things after that.

Upvotes: 1

Views: 12057

Answers (3)

user9433311
user9433311

Reputation:

Using Python we can do the following which is to fetch all the documents in a variable as mydoc

mydoc = collections.find()

for x in mydoc:
    l=list(x.keys())
    print(l)

Using this we can get all the keys as a list and then we can use them for further user's need

Upvotes: 2

Pynchia
Pynchia

Reputation: 11606

the document is a python dictionary so you can just print its keys

e.g.

document = db.collection_name.find_one()
for k in document:
    print(k)

Upvotes: -1

Sede
Sede

Reputation: 61273

As mentioned in the documentation:

In PyMongo we use dictionaries to represent documents.

So you can get all keys using .keys():

print(document.keys()) 

Upvotes: 2

Related Questions