1

I have a collection where all form data is stored, each form with a different structure, but some forms with overlapping field names. I love mongo for the ease it proves here, allowing me to sort and aggregate totally different data based upon a few small common factors.

Now, for the UI, I need a list of all possible fields in the database so a user can choose which fields to view. I can't seem to find any mongo anything to return a list of fields, except for indexes.

How would I go about this?

Community
  • 1
  • 1
Kavi Siegel
  • 2,964
  • 2
  • 24
  • 33

2 Answers2

4

There is no native MongoDB functionality that provides this information. MongoDB is completely schemaless and as such you will have to do a full database walk to compile a list of all unique field names.

The only possible workarounds are to store all fields using {field: <field name>, value: <field value>} pairs and run a distinct operation on "field" or to maintain a list of unique field names seperately in the database. Both have significant downsides.

Remon van Vliet
  • 18,365
  • 3
  • 52
  • 57
  • 3
    Another workaround would be to run a MapReduce as suggested for [StackOverflow: MongoDB Get names of all keys in collection](http://stackoverflow.com/questions/2298870/mongodb-get-names-of-all-keys-in-collection). If this is going to be done frequently as part of your application workflow, it would better to maintain a separate list of unique field names as suggested by Remon. You could generate a list of unique keys using [Variety, a Schema Analyzer for MongoDB](https://github.com/JamesCropcho/variety). – Stennie Jun 20 '12 at 12:22
  • Fair enough but building anything based on MongoDB JS context tends to be mutually exclusive with high performance. Additionally you cannot guarantee at any point in time that your unique fields list returned by m/r is current. That might not be relevant though. – Remon van Vliet Jun 20 '12 at 16:28
0

try this:

 db.collection_keys.distinct("_id")
Savior Nguyen
  • 87
  • 1
  • 10