Querying for a list of all distinct fields in Mong

2019-08-10 12:25发布

问题:

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?

回答1:

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.



回答2:

try this:

 db.collection_keys.distinct("_id")