6

Is there any way to get the list of keys of a particular document in MongoDB other than iterate through the document?

i.e I want to get the keys for the document returned by

db.users.find({username:'xyz@abc.com})

Are there any inline commands.If not,can anybody give an idea on how to do?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
user1429322
  • 1,266
  • 2
  • 24
  • 38

3 Answers3

5
Object.keys(db.users.findOne({username:'xyz@abc.com'}))

will return a list of all the keys of a particular document.

akki
  • 2,021
  • 1
  • 24
  • 35
3

I know I am a little bit late to the party here, but you can do this in the mongo shell by typing:

var entry = db["users"].findOne({username:'xyz@abc.com});
for (var key in entry) { print(key); }

The important piece is findOne, this way you grab the fields of the first document rather than a list of the matching documents. Then you can simply loop through and print the keys.

mgoldwasser
  • 14,558
  • 15
  • 79
  • 103
1

No, there's no such command. You have to fetch the document and process it in the app.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367